1

示例“高级 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.body 似乎从 req 对象树中丢失了吗?

会对我有很大的帮助。谢谢!

4

3 回答 3

0

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

代替

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

或者(直接使用express)

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");
});
于 2017-06-13T09:14:51.957 回答
0

亲爱的你将正文解析器 URL 编码设置为 true

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

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

于 2017-06-13T09:43:29.467 回答
-1

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)
}, ...
于 2017-06-13T07:58:44.633 回答