Fetch API how to get response body in catch?

醉酒当歌 提交于 2020-01-13 19:27:08

问题


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

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!


回答1:


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).



来源:https://stackoverflow.com/questions/43361789/fetch-api-how-to-get-response-body-in-catch

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!