Axios网络错误,ERR_CONNECTION_REFUSED:React/Node应用程序在本地运行良好,但在Heroku生产中出错

h4cxqtbf  于 2023-02-12  发布在  Node.js
关注(0)|答案(1)|浏览(239)

我有一个React/Node应用程序,它使用Axios发布到MongoDB Atlas。在本地,该应用程序可以成功调用,但在Heroku上部署后,我在控制台中收到以下错误消息:
POST http://本地主机网络::错误连接拒绝;未捕获(承诺中)o {消息:'网络错误',名称:'AxiosError',代码:错误_网络
React前端:

const handleClick = (event) => {
    event.preventDefault();
    const newConnection = {
        firstName: input.firstName, 
        lastName: input.lastName,
        email: input.email,
        comments: input.comments,
        date: new Date()
    }
    axios.post('http://localhost:3001/create', newConnection)
    
    window.alert("Thank you! We will be in touch soon.")
}

后端路由:

const express = require("express");
const router = express.Router();
const Connection = require("../models/connectionModel");
    
router.route("/create").post((req, res) => {
    const firstName = req.body.firstName;
    const lastName = req.body.lastName;
    const email = req.body.email;
    const comments = req.body.comments;
    const date = req.body.date;
    const newConnection = new Connection({
        firstName, 
        lastName,
        email,
        comments,
        date
    });

    newConnection.save();
})

module.exports = router;

后端服务器:

const express = require('express');
const app = express();
const cors = require('cors');
const mongoose = require('mongoose');
const path = require('path'); 
const port = process.env.PORT || 3001;

app.use(cors());
app.use(express.json());
app.use(express.static(path.resolve(__dirname, "./frontend/build")));

if (process.env.NODE_ENV !== 'production') {
    require('dotenv').config();
}

mongoose.connect(process.env.MONGODB_URI);

app.use("/", require("./routes/connectionRoute"));

app.listen(port, function() {
    console.log('express server is running on port 3001')
})

在搜索了Web以寻找解决方案后,我确认Express服务器正在端口3001上运行,并且启用了CORS。可能是我在www.example.com请求中使用的URL有问题,但我不确定如何继续。axios.post request, but I'm unsure how to proceed.
任何帮助将不胜感激!

y1aodyip

y1aodyip1#

您正在尝试调用localhost。部署后,您需要调用API url。
创建从react的环境变量获取API_URL的方法。

API_URL=https://your-heroku-url.com
axios.post(`${API_URL}/create`, newConnection)

相关问题