突然之间,我所有的项目都出现了这种情况。

每当我在nodejs中使用express和body-parser req发布帖子时。Body是一个空对象。

var express    = require('express')
var bodyParser = require('body-parser')

var app = express()

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded())

// parse application/json
app.use(bodyParser.json())

app.listen(2000);

app.post("/", function (req, res) {
  console.log(req.body) // populated!
  res.send(200, req.body);
});

通过ajax和邮递员,它总是空的。

但是通过curl

$ curl -H "Content-Type: application/json" -d '{"username":"xyz","password":"xyz"}' http://localhost:2000/

它按预期工作。

我尝试在前者中手动设置Content-type: application/json,但我总是得到400个坏请求

这快把我逼疯了。

我以为是身体解析器更新了一些东西,但我降级了,它没有帮助。

感谢任何帮助,谢谢。


当前回答

似乎如果你不使用任何encType(默认是application/x-www-form-urlencoded),那么你会得到文本输入字段,但你不会得到文件。

如果你有一个表单,你想发布文本输入和文件,然后使用多部分/表单数据编码类型,除此之外,使用多元中间件。Multer将解析请求对象并准备req。您的文件和所有其他输入字段将通过req.body获得。

其他回答

确保["key":" type", "value":" json"] & ["key":"Content-Type", "value":"application/x-www-form-urlencoded"]在你的邮差请求头中

我发现,它的工作时,发送内容类型

“应用程序/ json”

与服务器端结合 app.use (express.json ()) (正如@marcelocra指出的那样,2022年的版本将使用)

(旧版本供参考) app.use (bodyParser.json ());

现在我可以通过发送

var data = {name:"John"}
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("POST", theUrl, false); // false for synchronous request
xmlHttp.setRequestHeader("Content-type", "application/json");
xmlHttp.send(data);

结果在服务器上的request.body.name中可用。

在我的情况下,我使用Fetch API发送POST请求,在正文中,我发送了一个对象而不是字符串。

错误-> {body: {email: 'value'}}

我纠正了stringized body -> {body: JSON。Stringify ({email: 'value'})}

我今天遇到了这个问题,解决它的方法是删除Postman中的内容类型头!很奇怪。把它加到这里,说不定能帮到谁。

我在这里跟随BeerLocker教程:http://scottksmith.com/blog/2014/05/29/beer-locker-building-a-restful-api-with-node-passport/

我的输入中没有名字…我的请求是空的……很高兴这是完成的,我可以继续编码。谢谢大家!

Jason Kim的回答是:

所以与其

<input type="password" class="form-control" id="password">

我有这个

<input type="password" class="form-control" id="password" name="password">