【问题标题】:can't get response status code with JavaScript fetch [duplicate]无法使用 JavaScript 获取响应状态代码 [重复]
【发布时间】:2019-07-20 21:49:20
【问题描述】:

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

}

我需要获取状态码。

【问题讨论】:

  • 您在这里遇到了 CORS 错误……所以请继续阅读这意味着什么,以及需要做些什么来解决它。
  • 我把答案放在这里请检查。 stackoverflow.com/a/66940824/12553450
  • 你可以试试这个: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); } }

标签: javascript reactjs fetch postman http-status-codes


【解决方案1】:

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

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

不检查请求是否成功是一个常见的错误我wrote it up on my anemic little blog

【讨论】:

  • 当我的请求失败时,.then() 中的任何内容都不会运行。它直接catch()
  • @alimottaghian - 来自fetch 的承诺只拒绝网络错误,而不是 HTTP 错误。因此,如果您无法将请求发送到服务器,它将拒绝,但如果服务器响应(例如)404,它不会拒绝。
  • @MarioGonzalesFlores - 哇,Safari (link) 中缺少 很多 Response 对象,包括非常基本的东西 ok(正如你所指出的,status)。这太离谱了。最好不要支持fetch。人们应该如何知道提取是否有效?!
  • @MarioGonzalesFlores - 我不能代表 Mac OS 上的 Safari,但不幸的是 MDN 对 iOS Safari 的看法是错误的。它同时具有okstatus,至少从iOS v12.3.1 开始。我有filed an issue
【解决方案2】:

status 存在于 response 对象中。您可以将其放入您的第一个然后阻止

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

由于您返回的是response.json(),因此后续的thencatch 只会得到response.json() 的结果,这是响应的正文。

【讨论】:

  • 当我的请求失败时,.then() 中的任何内容都不会运行。它直接进入 catch()
  • 你可以尝试 return response.text() 代替,我遇到了完全相同的问题,直接去 catch 然后我意识到 ir 是响应
猜你喜欢
  • 2011-09-04
  • 2017-10-24
  • 2014-10-17
  • 2020-01-10
  • 2021-07-11
  • 1970-01-01
  • 1970-01-01
  • 2016-02-07
  • 2017-09-26
相关资源
最近更新 更多