如何在获取 API 中处理 HTTP 代码 4xx 响应
How to handle HTTP code 4xx responses in fetch api
我想知道当我们使用 ajax 函数时,我们应该如何处理来自后端的 400。我们可以在承诺解析函数中做出 if 语句,并检查 res 状态是否为 400。不同的方法是为获取制作包装服务,当我们从服务器获得 400 时,我们会抛出异常。如何处理这个问题?
我建议使用一个包装器来检查response.ok
如果响应代码为 2xx 则为真。
请注意 fetch()
MDN 页面中的此声明:
对成功 fetch(( 的准确检查将包括检查承诺已解决,然后检查 Response.ok 属性是否具有值为 true。HTTP 状态 404 不构成网络错误。
这是一个这样的包装器:
function fetchData() {
return fetch.apply(null, arguments).then(response => {
if (!response.ok) {
// create error object and reject if not a 2xx response code
let err = new Error("HTTP status code: " + response.status)
err.response = response
err.status = response.status
throw err
}
return response
})
}
这样,我们可以相应地处理所有类型的状态。
fetch(url, {
method: 'POST',
headers: headers,
body: JSON.stringify({ user_email: email }),
}).then((response) => {
return new Promise((resolve) => response.json()
.then((json) => resolve({
status: response.status,
ok: response.ok,
json,
})));
}).then(({ status, json, ok }) => {
const message = json.message;
let color = 'black';
switch (status) {
case 400:
color = 'red';
break;
case 201:
case 200:
color = 'grey';
break;
case 500:
default:
handleUnexpected({ status, json, ok });
}
})
灵感
将其合并到HTTP抽象中可能是个好主意。也许有某种options
论点:
const myFetch = (method, path, {headers, strictErrors, whatever}) => {
// fetch here, if strictErrors is true, reject on error.
// return a Promise.
}
myFetch('GET', 'somepath', {strictErrors: true})
.then(response => {})
.catch(err => { /* maybe 400 */ });
围绕fetch
的包装器通常是一个好主意,fetch
是一个相对低级的函数。正如直接在任何地方创建新的 XHR 对象不是一个好主意一样,我认为在应用程序的各个部分直接调用 fetch()
也不是一个好主意。在某些方面,它类似于全局变量。
我为此找到的最好的方法是将其包装在一个新的承诺中,如果response.ok
为假,则拒绝带有错误上下文的承诺。
/**
* Parses the JSON returned by a network request
*
* @param {object} response A response from a network request
*
* @return {object} The parsed JSON, status from the response
*/
function parseJSON(response) {
return new Promise((resolve) => response.json()
.then((json) => resolve({
status: response.status,
ok: response.ok,
json,
})));
}
/**
* Requests a URL, returning a promise
*
* @param {string} url The URL we want to request
* @param {object} [options] The options we want to pass to "fetch"
*
* @return {Promise} The request promise
*/
export default function request(url, options) {
return new Promise((resolve, reject) => {
fetch(endpoint + url, options)
.then(parseJSON)
.then((response) => {
if (response.ok) {
return resolve(response.json);
}
// extract the error from the server's json
return reject(response.json.meta.error);
})
.catch((error) => reject({
networkError: error.message,
}));
});
}
(https://github.com/github/fetch/issues/203 的热门评论(
相关文章:
- AngularJS$http重定向状态代码
- Http状态代码工厂AngularJs
- 有谁知道这行代码的输出是什么?$.get(“http://192.168.4.1:80/”, {pin:p}.
- Angular2 http.get代码不工作
- 如何在使用JavascriptCallbackBehavior时引发带有HTTP错误代码的WebFaultExcepti
- URL中包含特殊字符的HTTP状态代码
- 如何使用scalajs-angular获取请求的http状态代码
- ionic http获取到本地文件会给出http错误代码0
- 检查 http 响应代码以显示相应的失败消息
- 在封闭的 python 服务器上的 ajax 请求中获取 0 作为 Http 响应代码
- HTTP 状态代码 - Backbone.js 和 Jquery
- 间歇性 HTTP 403 禁止访问错误调用相同的 Ajax 代码
- parse.com 加载代码 HTTP 请求和查询
- 预检响应具有无效的 HTTP 状态代码 405 - AngularJS + Spring MVC
- 使用 ajaxError 全局处理程序显示 HTTP 状态代码 401 详细信息
- 如何从 Servlet 获得 HTTP JSON 响应后更改 HTML 代码
- http 状态代码 NodeJS/ExpressJS 错误
- $http.get 返回 HTTP 代码 401
- http.get 解析错误,代码:“HPE_UNEXPECTED_CONTENT_LENGTH”
- 如何在获取 API 中处理 HTTP 代码 4xx 响应