【问题标题】:Why is req.body always empty when using Postman to call Express using JSON?为什么使用 Postman 使用 JSON 调用 Express 时 req.body 总是为空?
【发布时间】:2019-06-26 06:04:19
【问题描述】:

我有一个像这样设置的简单快速服务器...

const PORT = process.env.PORT || 3001;
import express from "express";  // eslint-disable-line
import bodyParser from 'body-parser';

export class BaseApp{
    constructor(port){
        const p = port || PORT;
        this.express = express();
        this.express.use(bodyParser.json());
        this.express.listen(p, (err)=>{
            if (err) throw err;
            return console.log(`Healthcheck server is listening on ${port}`);
        });
    }
}

const SearchRoute = function(app) {
    const Router = express.Router();
    const HANDLE_POST = (req, res)=> {
        console.log("Metadata is " + JSON.stringify(req.body));
        res.send("done");
    };
    Router.post("/", HANDLE_POST);
    app.use("/search", Router);
};
export class SearchApp extends BaseApp{
    constructor(){
        super(PORT);
        SearchRoute(this.express);
    }
}
new SearchApp(); // eslint-disable-line no-new

当我运行和使用邮递员(在原始时选择了应用程序/json)并通过帖子提交时,终端显示...

Metadata is {}

虽然我的身体...

我已经确认我的标题是正确的

为什么身体是空的?

【问题讨论】:

  • 另一个注意事项,如果我转换为 application/x-www-form-urlencoded 它可以工作,但我需要 json
  • 卷曲也可以正常工作,所以我正在更改标题

标签: json express postman


【解决方案1】:

尝试使用“application/json”而不是“application/javascript”设置您的内容类型标头

【讨论】:

    猜你喜欢
    • 2016-02-15
    • 2020-07-11
    • 1970-01-01
    • 2021-12-08
    • 2015-10-07
    • 2020-03-04
    • 2018-02-03
    • 2017-06-11
    • 2019-02-08
    相关资源
    最近更新 更多