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

29

我正在尝试创建一个登录表单。当我使用Postman测试服务时,我将获得一个包含状态代码等信息的正文对象。

Postman Result

然而,使用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())
            });
    }

}

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


3
你在这里遇到了CORS错误...所以去了解一下它的含义,以及需要做什么来修复它。 - 04FS
我把答案放在这里,请检查。https://stackoverflow.com/a/66940824/12553450 - Mafei
你可以尝试这样写代码:async function fetchText() { let response = await fetch('url.php'); console.log(response.status); // 200 console.log(response.statusText); // OK if (response.status === 200) { let data = await response.text(); console.log(data); } } - Lepy
2个回答

61
状态码是响应对象上的status属性。另外,除非您在错误响应中使用JSON(当然有些人会这样做),否则在调用json之前需要检查状态码(或ok标志)。
fetch(`${baseUrl}api/user/login`, {
    credentials: "include", // ¹ See note below
    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(// ...

不检查请求是否成功是一个常见的错误,我在我的不太活跃的旧博客上 写了这个问题


你使用了withCredentials: true,但文档中说明应该使用credentials: "include"。(感谢aderchox指出这个问题。)


2
当我的请求失败时,.then() 中的任何内容都不会运行。它直接进入 catch()。 - ali mottaghian
2
@alimottaghian - fetch 方法中的 Promise 只会在网络错误时被拒绝,而不是 HTTP 错误。因此,如果您无法将请求发送到服务器,它将被拒绝,但如果服务器响应 (例如 404),则不会被拒绝。 - T.J. Crowder
1
使用ES6 fetch时,请使用credentials: 'include'而不是withCredentials: true - aderchox
1
@aderchox - 感谢您指出这一点!我只是复制了原始帖子中的内容,但您是对的。我在答案中也标记了这一点。(附注:fetch与 "ES6" 没有任何关系,它是Web平台,而不是JavaScript。) - T.J. Crowder

9

statusresponse对象中。您可以在第一个then块内获取它。

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

由于你返回的是 response.json() ,因此后续的thencatch只会获取到response.json(),即响应主体。


5
当我的请求失败时,.then() 中的任何内容都不会被执行,直接跳转到 catch()。 - ali mottaghian
你可以尝试使用response.text()来返回响应内容,我遇到了完全相同的问题,直接进入catch后才意识到是响应的问题。 - Nicolas Silva
请查看此链接 https://stackoverflow.com/a/66940824/12553450 - Mafei

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接