简体   繁体   中英

express.js req.body undefined in middleware

I'm currently facing a problem in my node application.

while trying to use middleware in a post request the req.body becomes undefined.

for example;

router.post('/newpost', ensureAuthenticated, createPost, upload.single('file'), async (req, res) =>{
    console.log(req.body);
}

async function createPost(req, res, next){
    console.log(req.body);
    next();
}

when the createPost function runs it logs req.body as undefined. but when req.body gets logged inside the router.post it is defined.

is it something i'm missing? or is this just not possible to do.

also i've ensured that i've included bodyparser and initialized it before my routes.

well, I've just tested and all works fine, with my suggestion in the comment

here's the content of my test:

my index.js

const express = require('express')

const router = express.Router()
const app = express()
const PORT = process.env.PORT || 3002

app.use(express.json())

const createPost = (req, res, next) => {
    console.log('createPost', req.body)
    next()
}

router.post('/newpost', createPost, (req, res) => {
    console.log('/nextpost', req.body)
    res.json({ message: 'ok' })
})

app.use('/', router)

app.listen(PORT, () => {
    console.log(
        `server ready at http://localhost:${PORT}`
    )
})

and a simple REST Client file

@HOST = http://localhost:3002

POST {{HOST}}/newpost
Content-Type: application/json

{
    "fname": "Bruno",
    "lname": "Alexandre",
    "nick": "balexandre"
}

and the result is

❯ node .\index.js
server ready at http://localhost:3002
createPost { fname: 'Bruno', lname: 'Alexandre', nick: 'balexandre' }
/nextpost { fname: 'Bruno', lname: 'Alexandre', nick: 'balexandre' }

and the response of the call

HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 16
ETag: W/"10-/VnJyQBB0+b7i4NY83P42KKVWsM"
Date: Tue, 26 Jan 2021 19:59:21 GMT
Connection: close

{
  "message": "ok"
}

screenshot (click for full image)

在此处输入图像描述


Warning

make sure you're passing Content-Type: application/json in your POST request, remember that you told Express that you wanted the body parsed as .json() so make sure it knows you're passing json as the request body

a bit more information... the req.body is only undefined if I do not use the parser, like:

在此处输入图像描述


Added

a GitHub repository with working solution > https://github.com/balexandre/so65907925

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM