Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why fetch return a response with status = 0?

I want to use fetch API to get a whole HTML document from URL.

let config = { method: 'GET', headers: {     'Content-Type': 'application/json',     'Accept': 'text/html',     'Accept-Language': 'zh-CN',     'Cache-Control': 'no-cache' }, mode: 'no-cors'};  fetch('http://www.baidu.com', config).then((res)=> { console.log(res);}).then((text)=> {}); 

When I run the code in chrome, It triggers a request and returns html in the chrome network tab. but fetch res return:

enter image description here

Why status is 0 and how can I get the correct res like the one in the chrome network ?

like image 537
pingfengafei Avatar asked Oct 21 '16 17:10

pingfengafei


1 Answers

On the no-cors part of config.mode:

no-cors — Prevents the method from being anything other than HEAD, GET or POST. If any ServiceWorkers intercept these requests, they may not add or override any headers except for these. In addition, JavaScript may not access any properties of the resulting Response. This ensures that ServiceWorkers do not affect the semantics of the Web and prevents security and privacy issues arising from leaking data across domains.

Effectively, the response you get from making such a request (with no-cors specified as a mode) will contain no information about whether the request succeeded or failed, making the status code 0. Removing mode from your fetch call will show that the CORS had in fact failed.

To find out what 0 means in your particular case, consult other SO answers.

like image 140
Brian Avatar answered Oct 02 '22 13:10

Brian