Express.js req.body 未定义 [英] Express.js req.body undefined

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

问题描述

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

I have this as configuration of my Express server

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.body 的路由示例:

But still when I ask for req.body.something in my routes I get some error pointing out that body is undefined. Here is an example of a route that uses req.body :

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

我读到这个问题是由于缺少 app.use(express.bodyParser()); 而引起的,但正如你所看到的,我在路由之前调用它.

I read that this problem is caused by the lack of app.use(express.bodyParser()); but as you can see I call it before the routes.

有什么线索吗?

推荐答案

2020 年 7 月更新

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

UPDATE July 2020

express.bodyParser() is no longer bundled as part of express. You need to install it separately before loading:

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().

You must make sure that you define all configurations BEFORE defining routes. If you do so, you can continue to use 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' });
});

这篇关于Express.js req.body 未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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