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

Node.js与React.js全栈博客部署:环境变量连接配置问题

全栈博客前后端部署连接配置方案

前端(React)配置

  • 用环境变量存储后端API地址,避免硬编码
    • 本地开发:在项目根目录创建.env.development文件,写入REACT_APP_API_URL=http://localhost:8080/api
    • 生产部署:在Heroku等平台的环境变量设置中添加REACT_APP_API_URL,值为后端部署后的完整API前缀(比如https://your-heroku-backend.herokuapp.com/api)
    • 代码中调用接口时,直接拼接这个变量:
      fetch(`${process.env.REACT_APP_API_URL}/posts`)
        .then(res => res.json())
        .then(data => console.log(data))
      
    • 注意:React的环境变量必须以REACT_APP_开头,否则打包工具无法识别

后端(Node.js)配置

  • 跨域必须处理,否则前端会出现跨域报错
    • 安装cors包:npm install cors
    • 在后端入口文件(比如server.js)中启用:
      const cors = require('cors');
      app.use(cors({
        origin: process.env.FRONTEND_URL || 'http://localhost:3000' // 本地默认前端地址
      }));
      
    • 部署时在平台环境变量中设置FRONTEND_URL为前端部署后的地址(比如https://your-react-frontend.herokuapp.com)
  • 端口不要硬编码,通过环境变量获取:
    const PORT = process.env.PORT || 8080;
    app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
    
  • 若要将前端打包后与后端一起部署,可直接用Express托管静态文件:
    const path = require('path');
    app.use(express.static(path.join(__dirname, 'client/build')));
    // 所有非API请求返回前端页面
    app.get('*', (req, res) => {
      res.sendFile(path.join(__dirname, 'client/build/index.html'));
    });
    

部署注意事项

  • Heroku部署后端时,package.json中必须包含start脚本:"start": "node server.js"
  • 前端单独部署时,先执行npm run build生成静态文件,再将build目录上传至静态托管平台
  • 测试时先单独验证后端API是否可正常访问,确认无误后再测试前后端连接

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 05:54:16