繁体   English   中英

req.body未显示为键值对之一,但req.header和其他

[英]req.body isn't appearing as one of key-value pairs, but req.headers and others do

示例“高级REST客户端”请求

我正在使用Postman和Advanced REST客户端为以下代码创建基本的POST请求-

'use strict';
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var http = require('http');

// configure the app to use bodyParser()
app.use(bodyParser.urlencoded({
    extended: false
}));
app.use(bodyParser.json());
//app.listen(6666);

http.createServer(function (req, res) {
    h2s(req, res);
}).listen(6666, '127.0.0.1');

console.log('Server running at http://127.0.0.1:6666/');

module.exports = function h2s(req, res) {
    console.log("inside h2s");
    app.use(function (req, res) {
        console.log("req.body : " + req.body);
        res.send("OK");
    });
}

但是,当我调试时,我发现“ req对象树”中缺少req.body。 更奇怪的是,我对req.headers所做的所有更改都在req对象树中可用。

看来我似乎犯了一个小错误,但我无法弄清楚。 经过一个小时左右的故障排除,但没有运气!

你们谁能弄清楚为什么req对象树中似乎缺少req.body?

将对我有很大帮助。 谢谢!

看起来您的代码中有几个问题:

代替

http.createServer(function (req, res) {
    h2s(req, res);
 }).listen(6666, '127.0.0.1');

console.log('Server running at http://127.0.0.1:6666/');

module.exports = function h2s(req, res) {
    console.log("inside h2s");
    app.use(function (req, res) {
    console.log("req.body : " + req.body);
    res.send("OK");
   });
}

要创建服务器,请尝试

http.createServer(app).listen(8000, '127.0.0.1'); //using http

或(直接使用快递)

app.listen(8000,function(){
    console.log('Server running at http://127.0.0.1:8000/');
});

然后为您的请求注册一个处理程序函数,您可以在其中访问req.body

app.use(function (req, res) {
    console.log("req.body : " + req.body);
    res.send("OK");
});

尊敬的您将主体解析器网址编码设置为true

// configure the app to use bodyParser()
app.use(bodyParser.urlencoded({
    extended: true
}));

并通过打印req.body进行检查,它对我有用,也可能对你有用

以下情况下也可以访问req.body

内容类型:“应用程序/ x-www-form-urlencoded”

读这个
在您的情况下,您的内容类型为application / json”

因此请尝试将内容类型更改为“ application / x-www-form-urlencoded”

从JS发送到服务器时,还要参数进行url编码

也可以解决

// fire request
request({
    url: url,
    method: "POST",
    json: true,
    headers: {
        "content-type": "application/json",
    },
    body: JSON.stringify(requestData)
}, ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM