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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…