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

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

这快把我逼疯了。

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

感谢任何帮助,谢谢。


当前回答

即使当我第一次学习node.js时,我开始在web-app上学习它,我在我的表单中以良好的方式完成了所有这些事情,但我仍然无法在post request中接收值。经过长时间的调试,我才知道,在我提供的形式enctype="multipart/form-data"由于我无法得到的值。我只是把它取下来,它就为我工作了。

其他回答

我解决了这个问题通过改变我的形式在前端的enctype:

它是⛔️<form enctype="multipart/form-data"> 我将其更改为✅<form enctype="application/json">

看到数据最终弹出控制台,我松了一口气^^

我使用的是restify而不是express,遇到了同样的问题。解决办法是:

server.use(restify.bodyParser());

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

Jason Kim的回答是:

所以与其

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

我有这个

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

我的问题是我先创建了路线

// ...
router.get('/post/data', myController.postHandler);
// ...

并且在路由之后注册中间件

app.use(bodyParser.json());
//etc

由于应用程序结构&复制和粘贴项目在一起的例子。

一旦我修正了在路由之前注册中间件的顺序,一切就都工作了。

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