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

向ngrok服务器发送Axios Post请求,为何req.body无数据?

问题核心原因

你遇到的req.body为空的问题,本质是请求数据格式和服务器的解析器不匹配:

  • 你给Axios设置了Content-type: application/x-www-form-urlencoded请求头,但直接传入了JSON对象{ title: 'world' },Axios不会自动把JSON转成urlencoded格式的字符串;
  • 服务器只配置了bodyParser.json(),只能解析JSON格式的请求体,完全处理不了urlencoded类型的数据,自然读不到req.body。
两种解决办法,选一个就行

办法1:改Axios请求,用JSON格式发送

既然服务器已经配了JSON解析器,直接用默认的JSON格式最省事:

  1. 删掉自定义的Content-type头(Axios发JSON时会自动加Content-type: application/json)
  2. 请求体保持JSON对象不变

修改后的Axios代码:

const posting = async () => {
  await axios.post('http://a410-xxx-c455-d1e8-1c8a-fa19.ngrok-free.app/someRequest',
    { title: 'world' }
  );
  // ...
}

办法2:改服务器配置,支持urlencoded格式

如果必须用application/x-www-form-urlencoded格式,得给服务器加对应的解析器,同时Axios要把JSON转成urlencoded字符串:

服务器端修改(index.js)

const app = require('./app');
const bodyParser = require('body-parser');
// 解析JSON格式
app.use(bodyParser.json());
// 新增解析urlencoded格式的配置
app.use(bodyParser.urlencoded({ extended: true }));

客户端Axios修改(先装qs库:npm install qs)

const qs = require('qs'); // 或者用import qs from 'qs'

const posting = async () => {
  await axios.post('http://a410-xxx-c455-d1e8-1c8a-fa19.ngrok-free.app/someRequest',
    qs.stringify({ title: 'world' }), {
      headers: {
        "Content-type": "application/x-www-form-urlencoded"
      }
    }
  );
  // ...
}
额外要改的地方

你routes.js里的路由写法有问题,app.use(router.post(...))是错误的,应该先定义路由再挂载:

// routes.js正确写法
router.post('/someRequest', (req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  console.log(req.body);
  res.sendStatus(200); // 记得返回响应,不然请求会一直挂着
});

app.use(router);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 22:57:49