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:
Why status is 0 and how can I get the correct res like the one in the chrome network ?
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.
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