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

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

这快把我逼疯了。

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

感谢任何帮助,谢谢。


当前回答

你不应该做JSON.stringify(数据)而通过AJAX发送如下。

这不是正确的代码:

function callAjax(url, data) {
    $.ajax({
        url: url,
        type: "POST",
        data: JSON.stringify(data),
        success: function(d) {
            alert("successs "+ JSON.stringify(d));
        }
    });
}   

正确的代码是:

function callAjax(url, data) {
    $.ajax({
        url: url,
        type: "POST",
        data: data,
        success: function(d) {
            alert("successs "+ JSON.stringify(d));
        }
    });
}

其他回答

在邮差的3个选项可用的内容类型选择“X-www-form-urlencoded”,它应该工作。

还可以摆脱错误消息替换:

app.use(bodyParser.urlencoded())

:

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

参见https://github.com/expressjs/body-parser

“体解析器”中间件只处理JSON和urlenencoded数据,而不是多部分

正如@SujeetAgrahari提到的,体解析器现在内置在express.js中。

使用app.use (express.json ());在JSON体的最新版本中实现它。对于URL编码的主体(由HTTP表单POSTs生成的那种)使用app.use(express.urlencoded());

我用上面建议的multer解决了这个问题,但他们没有给出一个完整的工作示例,关于如何做到这一点。基本上,当你有一个enctype="multipart/form-data"的表单组时,这种情况就会发生。下面是表单的HTML:

<form action="/stats" enctype="multipart/form-data" method="post">
  <div class="form-group">
    <input type="file" class="form-control-file" name="uploaded_file">
    <input type="text" class="form-control" placeholder="Number of speakers" name="nspeakers">
    <input type="submit" value="Get me the stats!" class="btn btn-default">            
  </div>
</form>

下面是如何使用multer来获取Express.js和node.js的值和名称:

var multer  = require('multer')
var upload = multer({ dest: './public/data/uploads/' })
app.post('/stats', upload.single('uploaded_file'), function (req, res) {
   // req.file is the name of your file in the form above, here 'uploaded_file'
   // req.body will hold the text fields, if there were any 
   console.log(req.file, req.body)
});

使用Postman,要测试带有原始JSON数据有效负载的HTTP post动作,请选择raw选项并设置以下报头参数:

Content-Type: application/json

另外,确保在JSON有效负载中用双引号包装任何用作键/值的字符串。

主体解析器包可以很好地解析多行原始JSON有效负载。

{
    "foo": "bar"
}

在Chrome v37和v41中使用Postman v0.8.4.13扩展(body-parser v1.12.2和express v4.12.3)测试,设置如下:

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

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

// ... Your routes and methods here

表达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();
};

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

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

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

助教:-)