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?
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.
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!
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 .
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...
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