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

请求成功却无法读取请求体?Node.js+Axios数据传输问题

问题原因及解决方案

你的问题出在Axios实例的配置与调用方式不匹配,导致请求数据没有被正确发送到服务器。

具体原因

你在axios.create()中设置了data参数,但随后调用writeFileApi.post('/')时没有传递数据,Axios并没有正确使用你在实例配置中定义的data。另外,虽然你设置了method: 'post',但调用post()方法时,需要明确传递请求体数据才能确保数据被发送。

修复方案

方案1:修改Axios调用方式(推荐)

直接在post()方法中传递请求数据,不要在实例创建时设置data:

const candidates = ['John Doe', 'Jane Doe', 'Bob Smith'];

const writeFileApi = axios.create({
  baseURL: 'http://localhost:3000',
  headers: {
    'Content-Type': 'application/json'
  }
});

writeFileApi.post('/', { candidates1: candidates })
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });

方案2:调整实例配置与调用方法

如果要在实例创建时定义data,需要使用request()方法发起请求,同时补充url配置:

const candidates = ['John Doe', 'Jane Doe', 'Bob Smith'];

const writeFileApi = axios.create({
  method: 'post',
  baseURL: 'http://localhost:3000',
  url: '/',
  headers: {
    'Content-Type': 'application/json'
  },
  data: { candidates1: candidates }
});

writeFileApi.request()
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });

额外检查项

  1. 跨域配置:如果你的React应用和Node.js服务器运行在不同端口(比如React默认3000,Node.js也用3000会冲突,通常React会改到3001),需要在Node.js中添加CORS支持:

    const cors = require('cors');
    app.use(cors());
    

    记得先安装cors包:npm install cors

  2. Body解析优化:Express 4.16+已经内置了JSON解析,你可以替换body-parser为内置方法,效果一致:

    // 替换 app.use(bodyParser.json());
    app.use(express.json());
    

完成以上修改后,服务器就能正常读取req.body.candidates1数组了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 21:22:54