You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React/Node应用本地正常,Heroku部署后出现Axios连接拒绝错误

问题分析与解决方案

核心问题

你遇到的ERR_CONNECTION_REFUSED完全是因为前端Axios请求硬编码了http://localhost:3001/create——部署到Heroku后,前端运行在Heroku的域名下,却依然尝试请求用户本地的3001端口,自然会连接失败。


分步修复

1. 修正Axios请求地址

把绝对路径改成相对路径,让请求自动适配当前部署环境的域名:

const handleClick = (event) => {
    event.preventDefault();
    const newConnection = {
        firstName: input.firstName, 
        lastName: input.lastName,
        email: input.email,
        comments: input.comments,
        date: new Date()
    }
    // 用相对路径替代硬编码的localhost地址
    axios.post('/create', newConnection)
        .then(() => window.alert("Thank you! We will be in touch soon."))
        .catch(err => window.alert(`Oops, something went wrong: ${err.message}`))
}

额外建议:给Axios请求添加catch处理,避免未捕获的Promise错误,同时能给用户更准确的反馈。

2. 修复后端路由的响应缺失

当前你的/create路由没有向前端返回任何响应,会导致请求挂起或超时。需要在保存数据后返回状态码和信息:

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()
        .then(() => {
            res.status(200).json({ message: "Connection saved successfully" });
        })
        .catch(err => {
            res.status(500).json({ error: err.message });
            console.error(err);
        });
})

3. 优化后端服务器配置

  • 动态输出监听端口:Heroku会分配随机端口,不是固定3001,所以日志要显示实际端口:
    app.listen(port, function() {
        console.log(`express server is running on port ${port}`)
    })
    
  • 添加前端路由 fallback:如果你的React应用用了React Router,直接访问子路由会返回404,需要添加:
    // 放在所有路由之后
    app.get('*', (req, res) => {
        res.sendFile(path.resolve(__dirname, "./frontend/build", "index.html"));
    });
    

4. 验证Heroku部署配置

确保你的package.json包含正确的启动脚本和构建脚本(前后端同仓库的情况):

{
  "scripts": {
    "start": "node server.js",
    "heroku-postbuild": "cd frontend && npm install && npm run build"
  }
}

内容的提问来源于stack exchange,提问作者jjjchou

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 03:31:36