Fetch API- res.json() returns an [object][object]

Viewed 1766

I've tried a lot of solutions I found, but with no success. I'm fetching the user object after authenticating-

Login.jsx-

const login = async () => {
    const res = await fetch('http://localhost:8080/login', {
        method: 'POST',
        credentials: 'include',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json;charset=UTF-8'
        },
        body: JSON.stringify({
            username: username,
            password: password
        })
    });
        
    const data = await res.json();
    
    console.log('data: ' + data); // [object][object]
}

routes.js

const handleLoginPost = (req, res, next) => {
    passport.authenticate('local', (err, user) => {

        if(err) {
            console.log(err);
            res.status(404).json({err});
            return;
        }

        res.status(200).json(user);
        return;

    })(req, res, next);
}

router.post('/login', handleLoginPost);

When I use res.text() instead res.json() then it returns a string object-

{"_id":"5f72cf2aa985f40488b2eb2b","username":"sapinder","email":"1@gmail.com","hash":"$2b$10$/7lYBHWP1Ed2VXXSIizyiOk.aujvbi2iRRrFxy6ufxu..S81oRl2u","__v":0}

It's a string because typeof data returns String in this case. I tried JSON.parse(data) but it again returns [object][object].

What's the correct method to extract the user object?

3 Answers

Change this:

console.log('data: ' + data) 

to this

console.log('data: ',  data) 

or to this:

console.log('data: ' + JSON.stringify(data)). 

Your console.log() was triggering a default string conversion of data. In Javascript, the default string conversion for an object is [Object object] which is generally useless. Your data is there, it's just your console.log() code that is faulty when trying to output it.

I'm not sure, but try with .then(data => console.log('data: ' + data))

try this one

const login = async () => {
    const res = await fetch('http://localhost:8080/login', {
        method: 'POST',
        credentials: 'include',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json;charset=UTF-8'
        },
        body: JSON.stringify({
            username: username,
            password: password
        })
    }).then((response) => {
    return response.json();
  }).catch((err)=>{
      console.log(err)
  });

  console.log("Res", res)
  return res;
}

Related