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

每当我在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个坏请求

这快把我逼疯了。

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

感谢任何帮助,谢谢。


当前回答

表达4.17.1

这样的服务器中间件示例没有bodyParser;

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

如果你是GET请求头应该是这样的;

{'Content-Type': 'application/json'}

如果你是POST请求头应该像这样;

{'Content-Type': 'application/x-www-form-urlencoded'}

我在客户端使用这样的简单函数;

async function _GET(api) {
    return await (await fetch(api, {
        method: 'GET',
        mode: 'no-cors',
        cache: 'no-cache',
        credentials: 'same-origin',
        headers: {
            'Content-Type': 'application/json; charset=utf-8',
            'Connection': 'keep-alive',
            'Accept': '*',
        },
    })).json();
};

async function _POST (api, payload) {
    return await (await fetch(api, {
        method: 'POST',
        mode: 'no-cors',
        cache: 'no-cache',
        credentials: 'same-origin',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Connection': 'keep-alive',
            'Accept': '*/*',
        },
        body: new URLSearchParams(payload),
    })).json();
};

其他回答

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

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

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

类似的问题发生在我身上,我只是混合了回调参数的顺序。确保以正确的顺序设置回调函数。至少对有同样问题的人来说是这样。

router.post('/', function(req, res){});

您必须检查主体解析器中间件是否正确地设置为请求的类型(json, urlencoded)。

如果你设置了,

app.use(bodyParser.json());

然后在邮差你必须发送原始数据。

https://i.stack.imgur.com/k9IdQ.png邮差截图

如果你设置了,

app.use(bodyParser.urlencoded({
    extended: true
}));

然后应该选择'x-www-form-urlencoded'选项。

改变app.use (bodyParser.urlencoded ());在代码中

app.use(bodyParser.urlencoded({extended : false}));

而在postman中,在header中更改Content-Type值为 Application /x-www-form-urlencoded为Application /json

助教:-)

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

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