Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch Request Completes Successfully, but Response Object Empty

I have a fetch request within the componentDidMount() method of a React component:

const request = new Request(url, {
    mode: 'no-cors',
    method: 'get',
    headers: {
        Accept: 'application/json'
    }
});

fetch(request)
    .then(function(response) {  
        console.log('Response: ', response);

        return response.text();  
    })
    .then(function(data) {
        // _this.setState({ data: data });

        console.log('Success: ', data);
        console.log('Request succeeded with JSON response', data);
    }).catch(function(error) {
        console.log('Request failed', error);
    });

When the Component loads, I can see the Request being made in the Console and the proper data being returned; however, my Response object is always empty:

Response { type: "opaque", url: "", redirected: false, status: 0, ok: false, statusText: "", headers: Headers, bodyUsed: false }

response.text() returns null, and I'm really uncertain what is going on. I've used the same method before and not had this problem, so I'm uncertain if it's different because of the third-party data source or what.

Any ideas?

like image 671
Eric R Avatar asked May 30 '17 17:05

Eric R


People also ask

What type of object does a fetch call return?

The response of a fetch() request is a Stream object, which means that when we call the json() method, a Promise is returned since the reading of the stream will happen asynchronously.

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!

What is response json () in fetch?

json() The json() method of the Response interface takes a Response stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON .


1 Answers

I suggest you to follow the comments below the question:

sideshowbarker says

If the reason you’re using mode: 'no-cors' is because the server doesn’t send the Access-Control-Allow-Origin response header in its responses, then mode: 'no-cors' is not the way to fix that. The only way to fix it properly is to either configure the server to send Access-Control-Allow-Origin response header or else change your frontend JavaScript code to make you request through a proxy instead. follow this link...

like image 130
Abdulbosid Avatar answered Sep 23 '22 06:09

Abdulbosid