Mehran Mehran - 4 months ago 14
Javascript Question

fetch's response is empty even though the request was successful

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?

Answer

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.

Comments