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

Express+Node.js接口在React+Axios调用时响应异常求助

问题:Express + Node.js HelloWorld接口在React中用Axios调用时出现响应异常(提示仅支持JSON数据)

我正在使用Express和Node.js开发一个HelloWorld接口,在ReactJS中通过Axios调用该接口时,遇到了响应异常问题。

服务端代码

var busboy = require('connect-busboy');
const app = express()
const port = 4002
app.use(bodyParser())
app.use(busboy());
app.use('/', express.static('./'));
app.get('/helloworld', (req, res) => {
  return res.send('hello world')
})

前端Axios调用代码

callWs = () => {
  axios.get(`http://localhost:4002/helloworld`)
  .then(response => {
    console.log('WS') // 此处未执行
  })
  .catch(function (error) {
    if (error.response) {
      console.log('Error data : ', error.response.data);
      console.log('Error status : ', error.response.status);
      console.log('Error headers : ', error.response.headers);
    } else if (error.request) {
      console.log('Error request : ', error.request);
    } else {
      console.log('Error message : ', error.message);
    }
    console.log(error.config);
  })
}

浏览器控制台提示:仅支持JSON数据。

请问该如何解决这个问题?谢谢。


解决方案

这问题我之前碰到过几次,大概率是Axios的默认响应解析规则和跨域配置的问题,咱们一步步来解决:

1. 先搞定跨域(隐藏的核心问题)

你的React前端通常跑在localhost:3000,后端在4002端口,属于跨域请求。浏览器会拦截这类请求,有时候错误提示会被包装成“仅支持JSON”这种模糊的信息。

先给Express加CORS支持:

  • 首先安装依赖:
npm install cors
  • 然后修改服务端代码,在路由前添加CORS中间件:
const cors = require('cors');
const app = express();

// 先加CORS,允许跨域请求
app.use(cors());

2. 调整bodyParser的使用(避免中间件冲突)

你直接用app.use(bodyParser())的写法已经过时了,而且可能和busboy中间件产生冲突,或者影响响应处理。换成Express内置的解析方法更稳妥:

// 替换原来的app.use(bodyParser())
app.use(express.json()); // 只解析JSON请求体
app.use(express.urlencoded({ extended: true })); // 解析URL编码的请求体

3. 解决Axios的响应格式问题

Axios默认期望接口返回JSON格式,但你的接口返回的是纯文本hello world,这会导致它解析失败抛出异常。有两种解决方式:

方式一:让接口返回JSON(推荐)

修改服务端的接口,返回标准JSON:

app.get('/helloworld', (req, res) => {
  return res.json({ message: 'hello world' });
})

然后前端就能正常在then里获取数据:

.then(response => {
  console.log('WS:', response.data.message); // 会打印"hello world"
})

方式二:告诉Axios接受纯文本响应

如果坚持返回纯文本,在Axios请求里明确指定响应类型:

axios.get(`http://localhost:4002/helloworld`, {
  responseType: 'text' // 告诉Axios这是文本响应,不要按JSON解析
})
.then(response => {
  console.log('WS:', response.data); // 正常打印"hello world"
})

4. 调整中间件顺序(避免意外问题)

把中间件按“CORS → 请求体解析 → 其他工具中间件 → 静态文件 → 路由”的顺序排列,确保逻辑正确:

const cors = require('cors');
const express = require('express');
var busboy = require('connect-busboy');

const app = express()
const port = 4002

app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(busboy());
app.use('/', express.static('./'));

app.get('/helloworld', (req, res) => {
  return res.send('hello world')
})

app.listen(port, () => {
  console.log(`Server running on port ${port}`)
})

按上面的步骤调整后,你的接口应该就能正常被Axios调用了。

内容的提问来源于stack exchange,提问作者Anaïs Saez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:52:30