I'm trying to use fetch
function to retrieve data from server in a client side Javascript code. And I'm using the polyfill version of fetch named whatwg-fetch
in a Chrome (which supports fetch internally).
Here's how I call the function:
//Called in a page loaded as http://localhost:3236/
fetch("http://localhost:8080/list", {
mode: 'no-cors',
credentials: "include",
})
.then(function(response) {
return response.json();
});
As you can see my application server is not the same as my resource server so I had to set the options for CORS. The problem is that the response
has got no content:
{
body: null,
bodyUsed: false,
headers: Headers,
ok: false,
status: 0,
statusText: "",
type: "opaque",
url: "",
}
It's in the case that when I turn to network panel and find the request sent, it seems all OK with Status of 200 and the requested data.
How can I find what the problem is?
To solve the "TypeError: Failed to fetch", make sure to pass the correct configuration to the fetch method, including the URL, HTTP method and headers, and verify that the server you're making a request to is setting the correct CORS headers with the response. Copied!
then(response => { // how to check if response has a body of type json? if (response. isJson()) return response. json(); });
Use the fetch() method to return a promise that resolves into a Response object. To get the actual data, you call one of the methods of the Response object e.g., text() or json() . These methods resolve into the actual data.
An opaque response is for a request made for a resource on a different origin that doesn't return CORS headers. With an opaque response we won't be able to read the data returned or view the status of the request, meaning we can't check if the request was successful or not.
The clue is in the opaque
key. The request was successful, but Chrome's CORS restrictions are preventing you from using the returned data. The no-cors
option is suspect; it shouldn't be necessary if your server is correctly configured for cross-origin requests.
N.B. If you've configured everything correctly but you're experiencing errors while testing the client locally, it may be sufficient to launch Chrome with the --disable-web-security
flag.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With