req.body 在帖子上为空 [英] req.body empty on posts

查看:18
本文介绍了req.body 在帖子上为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

突然之间,我所有的项目都发生了这种情况.

All of a sudden this has been happening to all my projects.

每当我使用 express 和 body-parser 在 nodejs 中发帖时,req.body 就是一个空对象.

Whenever I make a post in nodejs using express and body-parser req.body is an empty object.

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 和邮递员,它总是空的.

Via ajax and postman it's always empty.

但是通过 curl

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

它按预期工作.

我尝试在前者中手动设置 Content-type : application/json 但我总是得到 400 bad request

I tried manually setting Content-type : application/json in the former but I then always get 400 bad request

这让我发疯了.

我以为是 body-parser 中更新了一些东西,但我降级了它并没有帮助.

I thought it was that something updated in body-parser but I downgraded and it didn't help.

任何帮助表示赞赏,谢谢.

Any help appreciated, thanks.

推荐答案

在 Postman 中可用于内容类型的 3 个选项中选择X-www-form-urlencoded"它应该可以工作.

In Postman of the 3 options available for content type select "X-www-form-urlencoded" and it should work.

还要去掉错误信息替换:

Also to get rid of error message replace:

app.use(bodyParser.urlencoded())

与:

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

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

body-parser"中间件只处理 JSON 和 urlencoded 数据,不处理多部分

The 'body-parser' middleware only handles JSON and urlencoded data, not multipart

正如@SujeetAgrahari 所说,body-parser 现在内置于 express.js 中.

As @SujeetAgrahari mentioned, body-parser is now inbuilt with express.js.

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

Use app.use(express.json()); to implement it in recent versions for JSON bodies. For URL encoded bodies (the kind produced by HTTP form POSTs) use app.use(express.urlencoded());

这篇关于req.body 在帖子上为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆