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

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

这快把我逼疯了。

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

感谢任何帮助,谢谢。


当前回答

只是一个快速输入-我有同样的问题(失眠测试我的私人api),当我添加Content-Type: application/json时,它立即工作了。让我困惑的是,对于GET和POST请求,我所做的一切几乎都是一样的,但是PUT似乎不能工作。我真的真的希望这篇文章能帮助一些人走出调试的兔子洞!

其他回答

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

只是一个快速输入-我有同样的问题(失眠测试我的私人api),当我添加Content-Type: application/json时,它立即工作了。让我困惑的是,对于GET和POST请求,我所做的一切几乎都是一样的,但是PUT似乎不能工作。我真的真的希望这篇文章能帮助一些人走出调试的兔子洞!

我犯了一个非常愚蠢的错误,忘记在我的html文件中为输入定义名称属性。

所以与其

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

我有这个。

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

现在请求。正文是这样填充的:{password: 'hhiiii'}

我用上面建议的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)
});

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

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