You need to enable JavaScript to run this app. React应用请求Express服务器根路径无法获取JSON响应的问题
优惠活动
大模型
产品
解决方案
定价
更多

React应用请求Express服务器根路径无法获取JSON响应的问题

根路径Fetch请求JSON解析失败问题排查

我写了一段点击按钮打印Express服务器JSON响应的代码:按钮b1对应根路径/,按钮b2对应路径/a。请求/a这类非根路径时能正常打印JSON,但请求根路径/时,控制台报错:

Fetch error: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

Express 代码

const express = require('express');
const server = express();
const port = 8000;

server.get('/', (req, res) => {
    res.json({"foo1":"bar"}); 
  });
  
server.get('/a', (req, res) => {
    res.json({"foo1":"bar"}); 
});


server.listen(port,() => console.log(`http://localhost:${port}`))

React 代码

function func1(){

    fetch('/')
    .then(response => {
      console.log(response);
      return response.json();
    })
    .then(jsonData => console.log(jsonData))
    .catch(error => console.error("Fetch error:", error));

}

function func2(){

    fetch('/a')
    .then(response => {
      console.log(response);
      return response.json();
    })
    .then(jsonData => console.log(jsonData))
    .catch(error => console.error("Fetch error:", error));

}

function App(){
    return(
<>
    <button onClick={func1}>
        b1
    </button>

    <button onClick={func2}>
        b2
    </button>
    </>
    )
}

export default App;

package.json 配置

"proxy":"http://localhost:8000",

问题原因

这是React开发服务器的代理机制导致的:当请求根路径/时,React dev server会优先返回自己的index.html页面(根路径是React应用的默认入口),不会把请求转发到Express服务器。你拿到的响应实际是HTML文本,不是预期的JSON数据,调用response.json()自然会解析失败。

解决方案

有两种简单的解决办法:

  1. 修改Express接口路径
    把根路径的接口改成其他名称,比如/api,避免和React的根路径冲突:
    Express代码修改:
    server.get('/api', (req, res) => {
        res.json({"foo1":"bar"}); 
      });
    
    React的func1修改:
    fetch('/api')
    
  2. 自定义代理规则
    使用http-proxy-middleware配置更灵活的代理,让API请求转发到Express,页面请求由React处理:
    • 安装依赖:npm install http-proxy-middleware --save-dev
    • 在项目src目录下创建setupProxy.js文件,添加代码:
      const { createProxyMiddleware } = require('http-proxy-middleware');
      
      module.exports = function(app) {
        app.use(
          '/',
          createProxyMiddleware({
            target: 'http://localhost:8000',
            changeOrigin: true,
            bypass: function(req, res, proxyOptions) {
              // 如果是HTML请求,交给React处理;否则转发到Express
              if (req.headers.accept.indexOf('html') !== -1) {
                return '/index.html';
              }
            }
          })
        );
      };
      

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 22:14:52