提问者:小点点

无法在express js节点中获取请求负载


这是我的Node Express代码,

(function () {
    'use strict';
    var fs = require('fs');
    var cors = require('cors');
    var bodyParser = require('body-parser');
    var express = require('express'),
        app = express(),
        port = 8112;


    app.use(cors());
    app.use(bodyParser.urlencoded({ extended: true }));
    app.use(bodyParser.json());
    app.listen(port);


    app.route('/abc')
        .post(abc);


    function abc(req,res){
        console.dir(req.body);
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        res.sendStatus(200);
    }

})();

但我将请求正文作为

{}

但在我的网络选项卡在Chrome我可以看到请求有效负载。请注意选项在此POST调用之前被激发。

请求标头

POST/abchttp/1.1 host:localhost:8112连接:
保持活动内容-长度:11 pragma:no-cache cache-control:no-cache
来源:http://localhost:4200用户-代理:mozilla/5.0(Windows NT 10.0;win64;x64)applewebkit/537.36(KHTML,像Gecko)chrome/66.0.3359.181 safari/537.36
x-api-key:

请求有效载荷

{“dd”:“dd”}


共1个答案

匿名用户

您需要发送:content-type:application/JSON才能使bodyparser.JSON()工作,如果没有它,您的JSON负载将不会被解析,这就是为什么您会得到:{}

从文档中:

bodyParser对象公开各种工厂以创建中间件。当Content-Type请求标头与type选项匹配时,所有中间件都将使用已分析的正文填充Req.body属性;如果没有要分析的正文、内容类型不匹配或发生错误,则使用空对象({})填充。

使用.fetch的示例:

fetch('http://localhost:4200/dashboard', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({dd: 'dd'})
});