问题描述
使用此代码:
fetch('notExists') // <---- notice
.then(
function(response)
{
alert(response.status)
}
)
.catch(function(err)
{
alert('Fetch Error : ', err);
});
这个承诺解决.
它返回一个可以解析为该请求的响应的承诺,不管成功与否.
一个失败的 ajax 请求即使转到一个不存在的资源也得到解决,这不是很奇怪吗?
Isn't it strange that a failed ajax request is resolved even if it goes to an non-existing resource ?
我的意思是——接下来呢?fetch
到已关闭但仍获得已解决承诺的服务器?
I mean - what next ? a fetch
to a server which is down and still get a resolved promise ?
我知道我可以在 response
对象的 ok
属性中进行调查,但仍然 -
I know I can investigate at the ok
property at the response
object , but still -
问题
为什么会为完全错误的请求(非现有资源)解决提取问题.
Why do a fetch gets resolved for a completely bad request ( non existing resource ).
推荐答案
fetch()
调用只有在网络请求本身由于某种原因失败(找不到主机、没有连接、服务器没有响应,等等...).
A fetch()
call is only rejected if the network request itself fails for some reason (host not found, no connection, server not responding, etc...).
从承诺的角度来看,从服务器返回的任何结果(404、500 等...)都被认为是成功的请求.从概念上讲,您从服务器发出请求,服务器响应您,因此从网络的角度来看,请求成功完成.
Any result back from the server (404, 500, etc...) is considered a successful request from the promise point of view. Conceptually, you made a request from the server and the server answered you so from the networking point of view, the request finished successfully.
然后您需要测试该成功响应以查看是否有您想要的答案类型.如果您希望 404 被拒绝,您可以自己编写代码:
You need to then test that successful response to see if has the type of answer you wanted. If you want a 404 to be a rejection, you could code that yourself:
fetch('notExists').then(function(response) {
if (!response.ok) {
// make the promise be rejected if we didn't get a 2xx response
const err = new Error("Not 2xx response");
err.response = response;
throw err;
} else {
// go the desired response
}
}).catch(function(err) {
// some error here
});
您甚至可以制作自己的 myFetch()
,它会自动为您执行此操作(将任何非 200 响应状态转换为拒绝).
You could even make your own myFetch()
that just does this automatically for you (converts any non-200 response status to a rejection).
已解决的承诺背后的原因是什么?请求(非现有资源/服务器停机).
首先,服务器关闭不会产生成功的响应 - 会拒绝.
First off, server down will not generate a successful response - that will reject.
如果您成功连接到服务器,向其发送请求并返回响应(任何响应),则会生成成功响应.至于为什么"fetch()
接口的设计者决定基于此拒绝,如果不与实际参与该接口设计的人交谈,这有点难以说,但对我来说这似乎是合乎逻辑的.通过这种方式,拒绝会告诉您请求是否通过并得到有效响应.由您的代码决定如何处理响应.当然,您可以创建自己的包装函数来修改默认行为.
A successful response is generated if you successfully connect to the server, send it a request and it returns a response (any response). As for "why" the designers of the fetch()
interface decided to base the rejection on this, it's a bit hard to say without talking to someone who was actually involved in the design of that interface, but it seems logical to me. This way the rejection tells you whether the request got through and got a valid response. It's up to your code to decide what to do with the response. You can, of course, create your own wrapper function that modifies that default behavior.
这篇关于fetch 即使 404 也能解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!