im just in the first days of learning REST API’s with express. Why does this code console.logs user correctly { name: 'Test', id: 1 }, but when im sending response, i got [Object object] displayed on the screen. I also cannot access user properties, but if I JSON.stringify(user)), it has all the properties set.
Im using app.use(express.json()) right after the requires.
const users = []
router.post('/', (req, res) => {
const newUser = {
name: req.body.firstName, // firstName to nazwa inputu z 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 wit id ${req.params.id} ${user}`)
})
>Solution :
The issue is that when you call res.send(GET user wit id ${req.params.id} ${user}), you are trying to concatenate the string "GET user with id" with the req.params.id variable is a number, and then the user variable is an object.
When you concatenate an object with a string, JavaScript calls the toString() method of the object, which returns [object Object] instead of the object’s properties.
You can fix this by using JSON.stringify(user) instead of the user in response to get the JSON representation of the object if you want to see all the properties of the user object.
res.send(`GET user wit id ${req.params.id} ${JSON.stringify(user)}`)
Or you could use template literals and access the object’s property directly.
res.send(`GET user wit id ${req.params.id} ${user.name}`)
Be sure you have parsed the request’s body before accessing the values with req.body.firstName