Home > Software engineering >  res.send() displays [object object], can't access properties
res.send() displays [object object], can't access properties

Time:01-11

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}`)
    })

CodePudding user response:

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

CodePudding user response:

As @Andreas pointed, you are converting an Object to String.

If you want to see a representation of an object as a String, you can use JSON.stringify().

Do it this way instead:

const myObject = { a: 3 }
const myVariable = 4

console.log(`${myVariable} ${JSON.stringify(myObject)}`) // 4 {"a":3}

Applied to your code:

res.send(`GET user wit id ${req.params.id} ${JSON.stringify(user)}`)
  • Related