Response status = 0 using fetch polyfill with mode: 'no-cors'
I'm using fetch polyfill with 'no-cors' mode and getting response status 0. In developer tools I can see that response has the requested data.
Client side code:
const BASE_CONFIG = {
credentials: 'include',
mode: 'no-cors'
};
let checkStatus = (response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
var error = new Error(response.statusText);
error.response = response;
throw error;
}
};
function GET(url, urlParams={}, config={}) {
let requestConfig = {
method: 'get'
};
Object.assign(requestConfig, BASE_CONFIG, config);
return fetch(url, requestConfig)
.then(checkStatus)
.then(parseJSON);
}
GET('http://other.domain,{})
Beckend nodejs (Express.js) simplified response handler:
function getData(req, res) {
var responseData = {data: 'test'};
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.writeHead(200, {"Content-Type": "application/json"});
return res.end(JSON.stringify(responseData));
}
Any idea what I'm doing wrong? Thanks!
no-cors
mode is only to CDN content, such as scripts, CSS and image, you cannot be used for getting data,response.status = 0
is right behavior
I don't know if you are using file: protocol, but in this case you can get a response status 0.
Neither Chrome's nor Firefox's native implementation supports fetching local files
See : https://github.com/github/fetch/pull/92#issuecomment-140665932
For now, unfortunate as it is, file and ftp URLs are left as an exercise for the reader. When in doubt, return a network error.
See : https://fetch.spec.whatwg.org/#basic-fetch (file and ftp sub sections)