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

前端 未结 6 1111
广开言路
广开言路 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:07

    I know this is an older post, but I found what worked for me to fix this error was using the IP address of my server instead of using the domain name within my fetch request. So for example:

    #(original) var request = new Request('https://davidwalsh.name/demo/arsenal.json');
    #use IP instead
    var request = new Request('https://0.0.0.0/demo/arsenal.json');
    
    fetch(request).then(function(response) {
        // Convert to JSON
        return response.json();
    }).then(function(j) {
        // Yay, `j` is a JavaScript object
        console.log(JSON.stringify(j));
    }).catch(function(error) {
        console.log('Request failed', error)
    });
    
    0 讨论(0)
  • 2020-12-08 02:08

    I had my front-end code running in http://localhost:3000 and my API(Backend code) running at http://localhost:5000

    Was using fetch API to call the API. Initially, it was throwing "cors" error. Then added this below code in my Backend API code, allowing origin and header from anywhere.

    let allowCrossDomain = function(req, res, next) {
      res.header('Access-Control-Allow-Origin', "*");
      res.header('Access-Control-Allow-Headers', "*");
      next();
    }
    app.use(allowCrossDomain);
    

    However you should restrict the you origins in case of other environments like stage, prod.

    0 讨论(0)
  • 2020-12-08 02:10

    If you are use nginx try this

    #Control-Allow-Origin access
    
        # Authorization headers aren't passed in CORS preflight (OPTIONS) calls. Always return a 200 for options.
        add_header Access-Control-Allow-Credentials "true" always;
        add_header Access-Control-Allow-Origin "https://URL-WHERE-ORIGIN-FROM-HERE " always;
        add_header Access-Control-Allow-Methods "GET,OPTIONS" always;
        add_header Access-Control-Allow-Headers "x-csrf-token,authorization,content-type,accept,origin,x-requested-with,access-control-allow-origin" always;
    
        if ($request_method = OPTIONS ) {
            return 200;
        }
    
    
    0 讨论(0)
  • 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 <img>):

    fetch(request, {mode: 'no-cors'})
    .then(function(response) {
      console.log(response); 
    }).catch(function(error) {  
      console.log('Request failed', error)  
    });
    
    0 讨论(0)
  • 2020-12-08 02:21

    Look at https://expressjs.com/en/resources/middleware/cors.html You have to use cors.

    Install:

    $ npm install cors
    
    const cors = require('cors');
    app.use(cors());
    

    You have to put this code in your node server.

    0 讨论(0)
  • 2020-12-08 02:22

    This worked for me :

    npm install -g local-cors-proxy
    

    API endpoint that we want to request that has CORS issues:

    https://www.yourdomain.com/test/list
    

    Start Proxy:

    lcp --proxyUrl https://www.yourdomain.com
    
     Proxy Active 
    
     Proxy Url: http://www.yourdomain.com:28080
     Proxy Partial: proxy
     PORT: 8010
    

    Then in your client code, new API endpoint:

    http://localhost:8010/proxy/test/list
    

    End result will be a request to https://www.yourdomain.ie/test/list without the CORS issues!

    0 讨论(0)
提交回复
热议问题