Fetch API 如何获取响应体?

2022-01-20 00:00:00 fetch javascript

我从服务器收到这样的响应:

I got the response from server like this:

Request URL:http://api.bfexchange.net/wallet/balance
Request Method:GET
Status Code:504 Gateway Time-out
Remote Address:52.78.140.154:80
Referrer Policy:no-referrer-when-downgrade

但是在 fetch API 的 catch 中打印 err 只会返回 Error 对象.

But printing err in catch of fetch API just returns Error object.

fetch(...)
.then(...)
.catch((err) => {
    console.dir(err);
});

它打印这个(来自谷歌浏览器):

It prints this(from Google Chrome):

TypeError: Failed to fetch
    message: "Failed to fetch"
    stack: "TypeError: Failed to fetch"
    __proto__: Error
index.js:82 

我想获取状态代码以进行正确的错误处理,例如服务器没有响应.

I want to get status code to proper error handling, like server is not responding like something.

在这种情况下有没有办法获取响应数据?否则,我可以尝试哪些替代方案?

Is there a way to get response data in this case? Else, what alternatives can I attempt?

任何建议都会非常感激!

Any advice will very appreciate it!

推荐答案

如果服务器使用CORS,你会得到5xx响应,但不会作为拒绝;承诺将通过响应得到解决.如果服务器不使用 CORS,您将永远看不到响应,并且承诺将始终被拒绝(除非您使用no-cors",在这种情况下,您可以获得在某些服务工作者场景中有用的不透明响应).

If the server uses CORS you will get the 5xx response, but it won't be as a rejection; the promise will be resolved with the response. If the server does not use CORS, you won't ever see a response and the promise will always be rejected (unless you use "no-cors", in which case you can get an opaque response that is useful in some service worker scenarios).

相关文章