首页 > 解决方案 > 无法使用 JavaScript 获取响应状态代码

问题描述

我正在尝试创建一个登录表单。当我用 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())
            });
    }

}

我需要获取状态码。

标签: javascriptreactjsfetchpostmanhttp-status-codes

解决方案


状态码是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(// ...

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


推荐阅读