Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 548
Mehran Avatar asked Jul 10 '16 21:07

Mehran


People also ask

How do I fix fetch error in CORS?

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!

How do I know if a response is JSON?

then(response => { // how to check if response has a body of type json? if (response. isJson()) return response. json(); });

How do I get data from response fetch?

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.

What is an opaque response CORS?

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.


1 Answers

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.

like image 115
linguamachina Avatar answered Oct 09 '22 09:10

linguamachina