Express.js req.body undefined

2019-01-02 14:29发布

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

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);
});

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.

Any clue?

22条回答
看风景的人
2楼-- · 2019-01-02 15:06

Express 4, has build-in body parser. No need to install separate body-parser. So below will work:

export const app = express();
app.use(express.json());
查看更多
春风洒进眼中
3楼-- · 2019-01-02 15:06

Use app.use(bodyparser.json()); before routing. // . app.use("/api", routes);

查看更多
笑指拈花
4楼-- · 2019-01-02 15:07

You can try adding this line of code at the top, (after your require statements):

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

As for the reasons as to why it works, check out the docs: https://www.npmjs.com/package/body-parser#bodyparserurlencodedoptions

查看更多
看淡一切
5楼-- · 2019-01-02 15:07

If you are using some external tool to make the request, make sure to add the header:

Content-Type: application/json

查看更多
长期被迫恋爱
6楼-- · 2019-01-02 15:08

Latest versions of Express (4.x) has unbundled the middleware from the core framework. If you need body parser, you need to install it separately

npm install body-parser --save

and then do this in your code

var bodyParser = require('body-parser')
var app = express()

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())
查看更多
呛了眼睛熬了心
7楼-- · 2019-01-02 15:08

No. You need to use app.use(express.bodyParser()) before app.use(app.router). In fact, app.use(app.router) should be the last thing you call.

查看更多
登录 后发表回答