Origin http://localhost is not allowed by Access-Control-Allow-Origin

后端 未结 5 878
臣服心动
臣服心动 2020-12-05 20:29

I\'m trying to do a fetch from backbone.js to my node.js server. However, I get the following error in the console:

Origin http://localhost is not allowed by A

5条回答
  •  旧巷少年郎
    2020-12-05 20:44

    There are 2 calls that need to set the correct headers. Initially there is a preflight check so you need something like...

    app.get('/item', item.list);
    app.options('/item', item.preflight);
    

    and then have the following functions...

    exports.list = function (req, res) {
    Items.allItems(function (err, items) {
        ...
            res.header('Access-Control-Allow-Origin', "*");     // TODO - Make this more secure!!
            res.header('Access-Control-Allow-Methods', 'GET,PUT,POST');
            res.header('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept');
            res.send(items);
          }
       );
    };
    

    and for the pre-flight checks

    exports.preflight = function (req, res) {
    Items.allItems(function (err, items) {
            res.header('Access-Control-Allow-Origin', "*");     // TODO - Make this more secure!!
            res.header('Access-Control-Allow-Methods', 'GET,PUT,POST');
            res.header('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept');
            res.send(200);
        }
      );
    };
    

    You can consolidate the res.header() code into a single function if you want.

    Also as stated above, be careful of using res.header('Access-Control-Allow-Origin', "*") this means anyone can access your site!

提交回复
热议问题