Sorry if this question may sounds \"simple\", but I can\'t get body-parser
to work on this very simple example :
\"use strict\";
const PORT = 3000;
You're installing bodyparser as middleware after the route definition. Generally you want to define pre-route middlewares before the routes or separate routes out to different files.
Simply re-arrange your code as follows:
'use strict'
const PORT = 3000
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
app.use(bodyParser.json()) // note: this is before the route
app.post('/api/login', (req, res) => {
console.log(req.body)
if (!req.body) return res.sendStatus(400)
res.send('welcome, ' + req.body.username)
})
app.use(express.json())
console.log(`Listen on port ${PORT}`)
app.listen(PORT)
If you wish to use bodyparser in a separate file as a middleware, the common use is as follows:
routes/someroute.js
const bodyParser = require('body-parser')
const jsonParser = bodyParser.json()
module.exports = (app) => {
app.post('/a/route', jsonParser, (req,res) => {
...
})
}