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

Heroku应用显示JSON数据而非前端UI的问题解决

解决Heroku上前端UI与后端根路由冲突问题

核心方案

给后端API统一加上/api前缀,让Express优先托管前端静态文件,仅处理API路径的请求;非API请求全部转发到前端index.html,由前端路由接管。这样既保留前端根路由的UI展示,又不影响后端API功能。

1. 修改后端代码(backend.js)

  • 引入path模块,托管前端构建后的静态资源文件夹(通常是build或dist,路径根据你的项目结构调整)
  • 把原有根路由的API逻辑迁移到带/api前缀的路径下
  • 新增通配路由,所有非API请求返回前端index.html

示例代码:

const express = require('express');
const path = require('path');
const app = express();

// 托管前端静态资源
app.use(express.static(path.join(__dirname, 'client/build')));

// 所有API接口统一使用/api前缀
app.get('/api/home', async (req, res) => {
  // 原根路由的JSON返回逻辑
  res.json({ key: '后端API数据' });
});

// 非API请求全部转发到前端index.html
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'client/build', 'index.html'));
});

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`服务运行在端口 ${PORT}`));

2. 调整前端fetch请求

把原来请求根路径的代码,改成请求带/api前缀的后端接口:

// 原请求(冲突根源)
// fetch('/')
// 修改后
fetch('/api/home')
  .then(res => res.json())
  .then(data => {
    // 处理后端返回的JSON数据
  })
  .catch(err => console.error(err));

3. 配置package.json脚本(后端项目)

确保Heroku部署时自动构建前端项目,生成静态文件:

"scripts": {
  "start": "node backend.js",
  "build": "cd client && npm install && npm run build",
  "heroku-postbuild": "npm run build"
}
  • heroku-postbuild会在Heroku部署阶段自动执行,完成前端依赖安装和构建

4. 前端路由(App.js)无需修改

前端根路由/可以正常保留,现在后端会把所有非API请求转发到前端index.html,由React Router处理路由渲染:

import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Home from './pages/Home';
import OtherPage from './pages/OtherPage';

function App() {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/other" element={<OtherPage />} />
      </Routes>
    </Router>
  );
}

export default App;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 11:45:28