无法通过JavaScript获取获取响应状态代码

ali*_*ian 3 javascript http-status-codes fetch reactjs postman

我正在尝试创建一个登录表单。当我用Postman测试服务时,我会得到一个带有状态代码等的body对象。

邮递员结果

但是,通过JavaScript提取,我无法获取body对象,而我刚收到一个错误:

获取控制台日志

export const login = (username,password) => {
    return dispatch=>{
        const basicAuth = 'Basic ' + btoa(username + ':' + password);
        let myHeaders = new Headers();
            myHeaders.append('Authorization', basicAuth);
            myHeaders.append('Content-Type', 'application/json');      
            fetch(`${baseUrl}api/user/login`, {
                withCredentials: true,
                headers: myHeaders
            })
            .then(function (response) {
                return response.json();
            })
            .then(function (json) {
                dispatch(setLoginInfo(json))
            })
            .catch(err =>{
                console.log(err)
                 dispatch(loginFailed())
            });
    }

}
Run Code Online (Sandbox Code Playgroud)

我需要获取状态代码。

Pan*_*her 10

存在statusresponse对象中。你可以把它放在你的第一个 then 块中

.then(function (response) {
    console.log(response.status);
    return response.json();
})
Run Code Online (Sandbox Code Playgroud)

由于您正在返回response.json(),因此后续的then并且catch仅得到的结果response.json()是响应的正文。

  • 当我的请求失败时,.then() 中的任何内容都不会运行。它直接去catch() (5认同)

T.J*_*der 8

状态码是status响应对象上的属性。另外,除非您将JSON与错误响应一起使用(当然有人会这样做),否则您需要在调用之前检查状态代码(或okflagjson

fetch(`${baseUrl}api/user/login`, {
    withCredentials: true,
    headers: myHeaders
})
.then(function(response) {
    console.log(response.status); // Will show you the status
    if (!response.ok) {
        throw new Error("HTTP status " + response.status);
    }
    return response.json();
})
.then(// ...
Run Code Online (Sandbox Code Playgroud)

我经常在我贫乏的小博客上写出来的错误就是不能检查请求是否成功。

  • 当我的请求失败时,.then() 中的任何内容都不会运行。它直接去catch() (2认同)
  • @alimottaghian - 来自“fetch”的承诺仅拒绝**网络错误**,而不是 HTTP 错误。因此,如果您无法将请求发送到服务器,它会拒绝,但如果服务器响应(例如)404,它不会拒绝。 (2认同)

归档时间:

查看次数:

5895 次

最近记录:

6 年,9 月 前