Allow Access-Control-Allow-Origin header using HTML5 fetch API

前端 未结 6 1121
广开言路
广开言路 2020-12-08 01:57

I am using HTML5 fetch API.

var request = new Request(\'https://davidwalsh.name/demo/arsenal.json\');

fetch(request).         


        
6条回答
  •  一个人的身影
    2020-12-08 02:17

    Like epascarello said, the server that hosts the resource needs to have CORS enabled. What you can do on the client side (and probably what you are thinking of) is set the mode of fetch to CORS (although this is the default setting I believe):

    fetch(request, {mode: 'cors'});
    

    However this still requires the server to enable CORS as well, and allow your domain to request the resource.

    Check out the CORS documentation, and this awesome Udacity video explaining the Same Origin Policy.

    You can also use no-cors mode on the client side, but this will just give you an opaque response (you can't read the body, but the response can still be cached by a service worker or consumed by some API's, like ):

    fetch(request, {mode: 'no-cors'})
    .then(function(response) {
      console.log(response); 
    }).catch(function(error) {  
      console.log('Request failed', error)  
    });
    

提交回复
热议问题