简体   繁体   English

Node.js请求正文为空

[英]Node.js req.body is blank

I have tried the threads on Node "req is not defined" and req.body is empty when making a post request via http.request and similar, but the problem remains. 我已经尝试通过 http.request ”之 类的发布请求,节点“ req未定义”上的线程和req.body为空 ,但是问题仍然存在。

The server side code: 服务器端代码:

var express = require('express');  
var bodyParser = require('body-parser');  
var validator = require('validator');
var app = express();

app.use(bodyParser.urlencoded({ extended: false }));  
app.use(bodyParser.json());  
app.use(function(req, res, next) {  
    res.header("Access-Control-Allow-Origin", "*");
    next();
});

app.post('/sampleurl', function (req, res) {  
    var reqbody = req.body;
    console.log(reqbody);
});

app.listen(process.env.PORT);  
console.log("listening");

What I send (using hurl.it): 我发送的内容(使用hurl.it):

发布请求 响应

What I get back from the server (the console.log): 我从服务器获得的结果(console.log):

listening
{}

I just tried your code.. It is perfectly fine.. 我刚刚尝试了您的代码..很好。

What you are missing is adding headers in request. 您缺少的是在请求中添加标头。

Add Content-Type header as application/json Content-Type标头添加为application/json 在此处输入图片说明

To extend the other answer, which is correct, body-parser checks the Content-Type before trying to parse the HTTP body. 为了扩展另一个答案,这是正确的,body-parser在尝试解析HTTP正文之前检查Content-Type

If you'd like to change this behavior, you can have body-parser attempt to parse any input into json regardless of the Content-Type : 如果您想更改此行为,则可以使用body-parser尝试将任何输入解析为json,而与Content-Type无关:

app.use(bodyParser.json({ type: '*' }));

The wildcard * will tell it to try to parse on any type: https://github.com/expressjs/body-parser#bodyparserjsonoptions 通配符*会告诉它尝试解析任何类型: https : //github.com/expressjs/body-parser#bodyparserjsonoptions

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

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