Express.js req.body undefined

前端 未结 30 2754
半阙折子戏
半阙折子戏 2020-11-22 12:02

I have this as configuration of my Express server

app.use(app.router); 
app.use(express.cookieParser());
app.use(express.session({ secret: \"keyboard cat\" }         


        
30条回答
  •  余生分开走
    2020-11-22 12:20

    Building on @kevin-xue said, the content type needs to be declared. In my instance, this was only occurring with IE9 because the XDomainRequest doesn't set a content-type, so bodyparser and expressjs were ignoring the body of the request.

    I got around this by setting the content-type explicitly before passing the request through to body parser, like so:

    app.use(function(req, res, next) {
        // IE9 doesn't set headers for cross-domain ajax requests
        if(typeof(req.headers['content-type']) === 'undefined'){
            req.headers['content-type'] = "application/json; charset=UTF-8";
        }
        next();
    })
    .use(bodyParser.json());
    

提交回复
热议问题