我有这个作为我的快速服务器的配置

app.use(app.router); 
app.use(express.cookieParser());
app.use(express.session({ secret: "keyboard cat" }));
app.set('view engine', 'ejs');
app.set("view options", { layout: true });
//Handles post requests
app.use(express.bodyParser());
//Handles put requests
app.use(express.methodOverride());

但是当我在我的路由中请求req.body.something时,我得到了一些错误,指出body是未定义的。下面是一个使用req的路由示例。身体:

app.post('/admin', function(req, res){
    console.log(req.body.name);
});

我读到这个问题是由缺乏app.use(express.bodyParser())引起的;但你可以看到,我把它叫做路线之前。

有线索吗?


当前回答

2020年7月更新

express. bodyparser()不再捆绑为express的一部分。你需要在加载前单独安装:

npm i body-parser

// then in your app
var express = require('express')
var bodyParser = require('body-parser')
 
var app = express()
 
// create application/json parser
var jsonParser = bodyParser.json()
 
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
 
// POST /login gets urlencoded bodies
app.post('/login', urlencodedParser, function (req, res) {
  res.send('welcome, ' + req.body.username)
})
 
// POST /api/users gets JSON bodies
app.post('/api/users', jsonParser, function (req, res) {
  // create user in req.body
})

更多信息请看这里

原来是

在定义路由之前必须确定所有的配置。如果这样做,就可以继续使用express.bodyParser()。

举例如下:

var express = require('express'),
    app     = express(),
    port    = parseInt(process.env.PORT, 10) || 8080;

app.configure(function(){
  app.use(express.bodyParser());
});

app.listen(port);
    
app.post("/someRoute", function(req, res) {
  console.log(req.body);
  res.send({ status: 'SUCCESS' });
});

其他回答

你可以试着在顶部添加这行代码(在require语句之后):

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

至于为什么它起作用的原因,请查看文档:https://www.npmjs.com/package/body-parser#bodyparserurlencodedoptions

浪费了很多时间:

这取决于客户端请求中的Content-Type 服务器应该有不同的,以下app.use()之一:

app.use(bodyParser.text({ type: 'text/html' }))
app.use(bodyParser.text({ type: 'text/xml' }))
app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }))
app.use(bodyParser.json({ type: 'application/*+json' }))

来源:https://www.npmjs.com/package/body-parser bodyparsertextoptions

例子:

对我来说, 在客户端,我有以下标题:

Content-Type: "text/xml"

因此,在服务器端,我使用:

app.use(bodyParser.text({type: 'text/xml'}));

然后,要求。身体工作正常。

使用app.use (bodyparser.json ());在路由。/ /。 app.use(“/ api”,路线);

express.bodyParser()需要被告知它正在解析的内容类型。因此,您需要确保在执行POST请求时,包含了“Content-Type”标头。否则,bodyParser可能不知道如何处理POST请求的主体。

如果你使用curl来执行一个POST请求,其中包含一些JSON对象,它看起来会像这样:

curl -X POST -H "Content-Type: application/json" -d @your_json_file http://localhost:xxxx/someRoute

如果使用其他方法,请确保使用合适的约定设置报头字段。

好吧,这可能听起来很蠢,但对我来说很管用。

作为一个完全的初学者,我没有意识到写作:

router.post("/", (res, req) => {
  console.log(req.body);
  req.send("User Route");
});

是错的!

你必须确保你以正确的顺序传递post/get的参数(req,res):并相应地调用它们:

router.post("/", (req, res) => {
  console.log(req.body);
  res.send("User Route");
});