im currently developing api for user auth to consume by vue. and i already read some discussions about this topic but still confused what is the problem.
i already use express.json() and express.urlencoded and sort the order. testing it in postman and using morgan.
the result is request body returned back from postman is undefined (see in screen shot below) but morgan prints the request body successfully
javascript
const express = require("express");
const cookieParser = require('cookie-parser')
const session = require('express-session');
const morgan = require("morgan");
const router = express.Router()
const app = express();
const PORT = 3000;
// app.use(session({
// key: "user_id",
// secret: "secret",
// resave: false,
// saveUninitialized: false,
// cookie: {
// expires: 600000,
// },
// }))
router.use(express.json())
router.use(express.urlencoded({ extended: true }))
router.get('/hello', (req, res) => {
res.status(200).send('hello world')
})
// handle register request
router.post('/register', (req, res) => {
console.log(req.body.username, req.body.password)
res.status(200).json({
username: req.body.username,
password: req.body.password
})
})
//handle login request and check login state
router.post('/login', (req, res) => {
})
// handle logout
router.post('/logout', (req, res) => {
})
app.use(morgan('dev'))
app.use('/api', router)
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
console output:
[nodemon] 2.0.15
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node index.js`
Server is running on port 3000.
undefined undefined
POST /api/register?username=james&password=verystrongpassword 200 20.380 ms - 2
thanks for help
Repace body with params
Use req.params.username insted of req.body.username and same for password too
username: req.params.username,
password: req.params.password