无法使用 JavaScript fetch 获取响应状态代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/54900971/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 10:27:58  来源:igfitidea点击:

can't get response status code with JavaScript fetch

javascriptreactjsfetchpostmanhttp-status-codes

提问by ali mottaghian

I'm trying to create a login form. when I'm testing the service with Postman, I will get a body object with status code and etc.

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

Postman Result

邮递员结果

But, with JavaScript fetch, I can't get body object and I just received an error:

但是,使用 JavaScript fetch 时,我无法获取 body 对象,而且我刚刚收到一个错误:

fetch console log

获取控制台日志

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

}

I need to get status code in fetch.

我需要在 fetch 中获取状态代码。

回答by T.J. Crowder

The status code is the statusproperty on the response object. Also, unless you're using JSON with your errorresponses (which some people do, of course), you need to check the status code (or the okflag) before calling json:

状态代码是status响应对象的属性。此外,除非您在错误响应中使用 JSON (当然有些人会这样做),否则您需要在调用之前检查状态代码(或ok标志json

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(// ...

Not checking that the request succeeded is such a common mistake I wrote it up on my anemic little blog.

不检查请求是否成功是一个常见的错误,我把它写在我贫血的小博客上

回答by Panther

The statusis present in the responseobject. You can get it inside your first then block

status是存在于所述response对象。你可以把它放在你的第一个然后阻止

.then(function (response) {
    console.log(response.status);
    return response.json();
})

Since you are returning response.json(), the subsequent thenand catchonly gets the result of response.json()which is the body of the response.

由于您正在返回response.json(),因此后续thencatch仅获得response.json()响应主体的结果。