问题
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