Express.js req.body undefined

前端 未结 30 2500
半阙折子戏
半阙折子戏 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:24

    Wasted a lot of time:

    Depending on Content-Type in your client request
    the server should have different, one of the below 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' }))
    

    Source: https://www.npmjs.com/package/body-parser#bodyparsertextoptions

    Example:

    For me, On Client side, I had below header:

    Content-Type: "text/xml"
    

    So, on the server side, I used:

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

    Then, req.body worked fine.

提交回复
热议问题