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:
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…