I've just started learning about REST APIs with express. I am encountering a strange issue where the code successfully console logs { name: 'Test', id: 1 }
for the user, but when I send the response, it displays [Object object]
. Additionally, I am unable to access the user properties directly, but if I use JSON.stringify(user)
, all the properties are there.
I have included app.use(express.json())
right after the required modules.
const users = []
router.post('/', (req, res) => {
const newUser = {
name: req.body.firstName, // firstName is the input name in HTML
id: users.length + 1
}
const valid = true;
if (valid) {
users.push(newUser)
res.redirect(`/users/${newUser.id}`)
}
})
router.get('/:id', (req, res) => {
const user = users.find(elem => elem.id == req.params.id)
console.log(user)
res.send(`GET user with id ${req.params.id} ${user}`)
})