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

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

提交回复
热议问题