'How can I handle error with fetch for 204 No content?
I have a fetch request as below;
fetch(url, {
mode: 'no-cors',
credentials: 'include'
}).then((response) => {
if (response.ok) {
return;
}
console.log(`Something wrong`);
})
.catch((error) => {
console.log(`catch block error`);
});
My 204 response looks as
body: null
bodyUsed: false
headers: Headers {}
ok: false
redirected: false
status: 0
statusText: ""
type: "opaque"
url: ""
My question is how do I handle this since my 204 response is kind of successful, but only thing is the ok flag is false So it goes and prints "Something wrong" which is not correct for 204 response.
Solution 1:[1]
You said mode: 'no-cors' so you can't look at the response. no-cors mode is only useful if:
- you need to send a request
- the request doesn't need any features which would make it preflighted
- you don't need to know anything about the response
You can't read the status (this is why it is reported as 0 in the response you quoted), so you can't tell if it was 204 No Content or 200 OK or 500 Internal Server Error, etc.
You can't read the body, so you can't tell if there was no content by testing it.
You need to:
- Remove
mode: 'no-cors' - Make sure the server grants all the permissions you need using CORS
- Read the
statusproperty of the response object to determine if it is a204or not
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Quentin |
