无法在Express JS节点中获取请求有效负载 [英] Cant get request payload in express js node

查看:126
本文介绍了无法在Express JS节点中获取请求有效负载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的Node Express代码,

This is my Node Express Code,

(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调用之前会触发OPTIONS.

But in my network Tab in Chrome I can see request payload. Please note OPTIONS is fired before this POST call.

请求标头

POST/abcHTTP/1.1主机:localhost:8112连接:
keep-alive内容长度:11语法:无缓存缓存控制:无缓存
来源: 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:CExkxDlFC35ckfCGX6m61x76GxIYH2h2Iv8bX874
内容类型:文本/纯文本;字符集= UTF-8
接受:/引荐来源: http://localhost:4200/dashboard 接受编码:gzip,deflate,br
接受语言:en-US,en; q = 0.9

POST /abcHTTP/1.1 Host: localhost:8112 Connection:
keep-alive Content-Length: 11 Pragma: no-cache Cache-Control: no-cache
Origin: http://localhost:4200 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36
x-api-key:CExkxDlFC35ckfCGX6m61x76GxIYH2h2Iv8bX874
Content-Type:text/plain;charset=UTF-8
Accept: / Referer: http://localhost:4200/dashboard Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9

请求有效载荷

{"dd":"dd"}

{"dd":"dd"}

推荐答案

您需要发送:Content-Type: application/json以使bodyParser.json()工作,如果没有它,您的JSON有效负载将不会被解析,这就是您得到的原因:{}

You need to send: Content-Type: application/json for bodyParser.json() to work, without it, your JSON payload won't be parsed, that's why you get: {}

来自文档:

bodyParser对象公开了各种工厂来创建中间件. 所有中间件都将使用已解析的填充req.body属性 当Content-Type请求标头与type选项匹配时为主体,或者 一个空对象({}),如果没有要解析的正文,则为Content-Type 不匹配,或发生错误.

The bodyParser object exposes various factories to create middlewares. All middlewares will populate the req.body property with the parsed body when the Content-Type request header matches the type option, or an empty object ({}) if there was no body to parse, the Content-Type was not matched, or an error occurred.

使用.fetch的示例:

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

这篇关于无法在Express JS节点中获取请求有效负载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆