0

I am sending response from the node server api side as below: 1)res.status(200).send({success: true, token: 'JWT ' + token}); and 2) res.status(401).send({success: false, msg: 'Authentication failed. Wrong password.'}); When try to get the response back in below react client side function it gives me the json body sent but, it gives me status code as 'undefined':

login(userCredentials) {
    // Get a token from api server using the fetch api
    return this.fetch(`${this.domain}/api/login`, {
        method: 'POST',
        headers: new Headers({'Content-Type':'application/json'}),
        body: JSON.stringify(userCredentials)
    }).then((res) => {
          console.log('statusCode:'+ res.status)
          console.log('Token:' +res.token)
          this.setToken(res.token) // Setting the token in localStorage
          return Promise.resolve(res);

    })
}

Console Output:

statusCode: undefined 
Token: JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjozLCJlbWFpbCI6ImFkbWluQGRyci5jb20iLCJuYW1lIjoiQWRtaW4iLCJwYXNzd29yZCI6IiQyYiQxMCRGY2t3YVNTdG5DVy8xdUZ6Vko3N3VldFM2VFZydmdINVZkYXBnNGZ0RjB5aTFhYWYuZWFZZSIsInJvbGUiOiJBZG1pbiIsImNyZWF0ZWRBdCI6IjIwMTgtMTAtMThUMTM6NDM6MjQuMjUwWiIsInVwZGF0ZWRBdCI6IjIwMTgtMTAtMThUMTM6NDM6MjQuMjUwWiIsImlhdCI6MTUzOTk3NTM3MH0.oGIBXR56gGg1i5npGPgsZkSFxOMup9yY1Sa-D7unikA

How can I get both status code and json body in react client from the response sent by node server?

Vijesh
  • 795
  • 3
  • 9
  • 23
  • In your server code `res.status` is a function, and you're passing it `200` (`OK`). The object you're sending back (i.e. `{success: true, token: 'JWT}` doesn't contain a `status` key, so it's not available in the UI. – lux Oct 19 '18 at 19:29
  • Is `status` a key in your response? I see `success` and `token`. – wdm Oct 19 '18 at 19:30
  • I think the response object in express: res.status(statusCode).send(JsonBody) returns the status code mentioned in status and the json body mentioned in send.@lux – Vijesh Oct 19 '18 at 19:36

1 Answers1

0

Try this

login(userCredentials) {
    // Get a token from api server using the fetch api
    return this.fetch(`${this.domain}/api/login`, {
        method: 'POST',
        headers: new Headers({'Content-Type':'application/json'}),
        body: JSON.stringify(userCredentials)
    }).then(res => return res.json())
    .then((res) => {
          console.log('statusCode:'+ res.status)
          console.log('Token:' +res.token)
          this.setToken(res.token) // Setting the token in localStorage
          return Promise.resolve(res);

    })
}
Hemadri Dasari
  • 32,666
  • 37
  • 119
  • 162