58

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 ?

xpy
  • 5,481
  • 3
  • 29
  • 48
pingfengafei
  • 829
  • 2
  • 8
  • 12

1 Answers1

72

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.

Brian
  • 7,394
  • 3
  • 25
  • 46
  • 4
    Thx, if I remove 'no-cors': Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8888' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. how to solve the CORS? – pingfengafei Oct 22 '16 at 00:53
  • 2
    That is correct. CORS is a browser safety feature that cannot be disabled from the page itself. You must contact baidu.com if you want to request their pages from your browser. – Brian Oct 22 '16 at 15:42
  • 52
    Welcome to the insane and wonderful world of CORS. A necessary(?) evil; CORS is a huge pain the ass for web developers. – RyanNerd Feb 24 '18 at 01:16