I have a react/redux application and I'm trying to do a simple GET request to a sever:
fetch('http://example.com/api/node', { mode: "no-cors", method: "GET", headers: { "Accept": "application/json" } }).then((response) => { console.log(response.body); // null return dispatch({ type: "GET_CALL", response: response }); }) .catch(error => { console.log('request failed', error); });
The problem is that the response body is empty in the .then()
function and I'm not sure why. I checked examples online and it looks like my code should work so I'm obviously missing something here. The thing is, if I check the network tab in Chrome's dev tools, the request is made and I receive the data I'm looking for.
Can anybody shine a light on this one?
EDIT:
I tried converting the reponse.
using .text()
:
fetch('http://example.com/api/node', { mode: "no-cors", method: "GET", headers: { "Accept": "application/json" } }) .then(response => response.text()) .then((response) => { console.log(response); // returns empty string return dispatch({ type: "GET_CALL", response: response }); }) .catch(error => { console.log('request failed', error); });
and with .json()
:
fetch('http://example.com/api/node', { mode: "no-cors", method: "GET", headers: { "Accept": "application/json" } }) .then(response => response.json()) .then((response) => { console.log(response.body); return dispatch({ type: "GET_CALL", response: response.body }); }) .catch(error => { console.log('request failed', error); }); // Syntax error: unexpected end of input
Looking in the chrome dev tools:
The Response interface of the Fetch API represents the response to a request. You can create a new Response object using the Response() constructor, but you are more likely to encounter a Response object being returned as the result of another API operation—for example, a service worker FetchEvent.
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 just ran into this. As mentioned in this answer, using mode: "no-cors"
will give you an opaque response
, which doesn't seem to return data in the body.
opaque: Response for “no-cors” request to cross-origin resource. Severely restricted.
In my case I was using Express
. After I installed cors for Express and configured it and removed mode: "no-cors"
, I was returned a promise. The response data will be in the promise, e.g.
fetch('http://example.com/api/node', { // mode: 'no-cors', method: 'GET', headers: { Accept: 'application/json', }, }, ).then(response => { if (response.ok) { response.json().then(json => { console.log(json); }); } });
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