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
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!