为什么使用Postman通过JSON调用Express时req.body始终为空?

时间:2019-02-01 16:18:25

标签: json express postman

我有一个像这样的简单快递服务器...

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

当我运行并使用邮递员(原始且选择了application / json)并通过邮递提交时,终端显示...

Metadata is {}

即使我的身体是...

enter image description here

我确认我的标题正确

enter image description here

为什么身体空了?

1 个答案:

答案 0 :(得分:1)

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