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

Express接收Postman或cURL的POST请求时request.body为空如何解决

问题原因

你使用的express.json()中间件仅支持解析请求头Content-Type为application/json的请求体,你当前Postman的请求配置不符合该要求,因此无法解析到请求参数,导致req.body为空。

解决方案
  • 方案1:调整Postman请求格式匹配JSON解析规则

    1. 打开对应POST请求的Body标签页,选择raw选项
    2. 右侧格式下拉菜单选择JSON
    3. 输入框内填写合法JSON格式的请求参数,示例如下:
    {
      "username": "test",
      "password": "123456"
    }
    

    重新发送请求即可拿到对应的req.body内容。

  • 方案2:添加对应中间件支持其他请求格式
    如果你需要接收x-www-form-urlencoded格式的参数,在路由注册前添加如下中间件:

    app.use(express.urlencoded({ extended: true }));
    

    如果你需要接收form-data格式的参数,需要引入multer中间件处理:

    1. 先安装依赖:npm install multer
    2. 代码调整如下:
    const express= require('express');
    const multer = require('multer');
    const upload = multer();
    const app = express();
    
    app.use(express.json())
    app.use(express.urlencoded({ extended: true }))
    
    // upload.none()用于处理纯文本form-data请求
    app.post('/', upload.none(), (req,res)=>{
        res.json(req.body);
    });
    
    app.listen(3000)
    
验证方式

你可以通过curl命令快速验证JSON接口是否正常:
curl -X POST -H "Content-Type: application/json" -d '{"test":"demo"}' http://localhost:3000
正常请求会返回{"test":"demo"}即代表配置正确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 10:00:00