作为响应获取“未定义”状态代码

时间:2018-10-19 19:24:35

标签: node.js reactjs fetch react-fullstack

我正在从节点服务器api端发送响应,如下所示: 1)res.status(200).send({success: true, token: 'JWT ' + token}); 和2)res.status(401).send({success: false, msg: 'Authentication failed. Wrong password.'}); 当尝试在响应客户端功能下面获取响应时,它给了我发送的json正文,但给了我状态代码为 '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);

    })
}

控制台输出:

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

如何从节点服务器发送的响应中同时获取状态代码和json主体在React Client中?

1 个答案:

答案 0 :(得分:0)

尝试一下

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);

    })
}