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 Access-Control-Allow-Origin.
I added the following to my node.js server:
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', "http://localhost");
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
};
app.configure(function() {
app.use(allowCrossDomain);
});
But it's still returning the same error. However, even if this did work, it doesn't seem like the ideal solution, as I would like users from all over to be able to send requests.
There Are Two Approaches to Getting It Right.Use a reverse proxy server or WSGI server(such as Nginx or Apache) to proxy requests to your resource and handle the OPTIONS method in the proxy. Add support for handling the OPTIONS method in the resource's code.
1. Use the proxy setting in Create React App. "proxy": "https://cat-fact.herokuapp.com/", Now when you make an API request to https://localhost:3000/api/facts Create React App will proxy the API request to https://cat-fact.herokuapp.com/facts and the CORS error will be resolved.
Limiting the possible Access-Control-Allow-Origin values to a set of allowed origins requires code on the server side to check the value of the Origin request header, compare that to a list of allowed origins, and then if the Origin value is in the list, set the Access-Control-Allow-Origin value to the same value as ...
In that case you can change the security policy in your Google Chrome browser to allow Access-Control-Allow-Origin. This is very simple: Create a Chrome browser shortcut. Right click short cut icon -> Properties -> Shortcut -> Target.
If you want everyone to be able to access the Node app, then try using
res.header('Access-Control-Allow-Origin', "*")
That will allow requests from any origin. The CORS enable site has a lot of information on the different Access-Control-Allow headers and how to use them.
I you are using Chrome, please look at this bug bug regarding localhost and Access-Control-Allow-Origin. There is another StackOverflow question here that details the issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With