【发布时间】:2017-12-14 21:35:54
【问题描述】:
我正在使用here 指定的本机提取库。似乎每当返回 200 OK 以外的响应时,它都会抛出字符串响应 Uncaught (in promise) TypeError: Failed to fetch 的异常。
有没有办法捕获特定的 HTTP 响应代码并对其进行分支并仍然查看响应数据?例如 401 响应?
我附上了我用作提取包装器的请求代码。
static request(url, data) {
let headers = {
"Authorization": window.localStorage.getItem("Authorization"),
"Content-Type": "application/json"
};
let options = {
method: "GET",
headers: headers,
mode: "no-cors",
cache: "no-cache",
};
if (data) {
options = {
method: "POST",
headers: headers,
mode: "no-cors",
cache: "no-cache",
body: JSON.stringify(data)
}
}
return new Promise(async (resolve, reject) => {
try {
let response = await fetch(url, options);
let jsonResponse = await response.json();
return resolve(jsonResponse);
} catch (error) {
// hashHistory.push("/login");
return reject(error);
}
})
}
【问题讨论】:
-
一般来说,您永远不需要自己构造
Promise对象。您可以直接在request函数中等待fetch。 -
我认为这是问题的主要根源!感谢代码审查
标签: javascript http fetch-api ecmascript-2017