I'm using ReactJS for the Front end rendering of my site and using Meteor JS for server and everything else.
I'm calling a OAuth API on the client side...I get the following result:
Failed to load resource: Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin.
How do I fix this?
If it's your own API, add a CORS header allowing that origin. Here's an example that allows every origin. It must be run on the server:
WebApp.connectHandlers.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
If it's not your API, make the request on the server (Servers can ignore CORS) via a Meteor method and return the result to the client
Related
I have made simple expressJS server with nodemailer and have hosted it on aws elastic beanstalk, after which I was provided a 'http' link for the same, but I entered that link in my website which was hosted on netlify, it threw an error stating that an 'https' website cannot access 'http' website, so I converted my aws link to 'https' link, but after that I got an cors error from my netlify website.
I've tried multiple things, including importing the cors library from express like this:
`
const corsOptions = {
origin: [
/\.netlify\.app$/,
],
methods: ['GET', 'POST']
}
app.use(cors(corsOptions));
`
or setting headers like:
`
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
but these methods did not work either, I always get the same error:access has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.`
Please Help me resolve this error, I want to enable cors.
Thanks to Derviş Kayımbaşıoğlu for helping me.
If anyone is facing this issue, kindly check your load balancer settings, it requires a https redirect to http, so the port for https is '443' and for http(instance port) is '80'.
I have a React application and Nodejs(Express) in the Backend. After deploying to the host server, The function I did for updating some documents stop working properly. It gives the CORS error:
I have this line of code to handle CORS policy in my server.js:
app.use((req, res, next) => {
res.set({"Access-Control-Allow-Origin" : "*",
"Access-Control-Allow-Methods" : "HEAD, OPTIONS, GET, POST, PUT, PATCH, DELETE",
"Access-Control-Allow-Headers" : "Content-Type, Authorization, X-Requested-With"})
next();
});
It is ok for GET and POST methods but does not work for PUT (Don't know if Delete works haven't tried)
I am on this issue for plenty of time; tried this: https://stackoverflow.com/a/42463858/11896129
looked for a bunch of solutions on the net, tried to configure it from IIS web.config file, nothing resolve my problem. Which part may I miss?
As stated on MDN:
Additionally, for HTTP request methods that can cause side-effects on server's data (in particular, for HTTP methods other than GET, or for POST usage with certain MIME types), the specification mandates that browsers "preflight" the request, soliciting supported methods from the server with an HTTP OPTIONS request method, and then, upon "approval" from the server, sending the actual request with the actual HTTP request method.
So you do have to answer preflight requests:
app.options("*", (req, res) => {
res.status(200).send("Preflight request allowed");
});
Read more about preflight requests here.
This should work, I used this CORS configuration
app.use(function(req,res,next){
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, PATCH");
res.header("Access-Control-Allow-Headers", "Accept, Content-Type, Authorization, X-Requested-With");
next();
});
Most likely the error No 'Access-Control-Allow-Origin' header is present that you see is coming from the preflight OPTIONS request, which is most likely not even reaching your express backend but is being hanlded by webserver in the front.
Either arrange for OPTIONS requests also to be relayed to your express backend in your webserver configuration or instruct the webserver to respond to it with required headers.
Check these:
https://support.plesk.com/hc/en-us/articles/115001338265-How-to-set-up-CORS-cross-origin-resource-sharing-in-Plesk-for-Linux-
https://support.plesk.com/hc/en-us/articles/360005431913-Is-it-possible-to-enable-CORS-cross-origin-resource-sharing-on-Plesk-for-Windows
https://talk.plesk.com/threads/iis-cors-configuration-problem-for-node-js-backend.355677/
You can use npm package cors (https://www.npmjs.com/package/cors) in your project. Install it and then configure it as a middleware. And put it before your application routes.
const cors = require("cors");
const corsOptions = { origin: "*", methods:
"GET,HEAD,PUT,PATCH,POST,DELETE", allowedHeaders:
"Access-Control-Allow-Headers,Access-Control-Allow-Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Origin,Cache-Control,Content-Type,X-Token,X-Refresh-Token", credentials: true, preflightContinue: false,
optionsSuccessStatus: 204 };
app.use(cors(corsOptions));
Please try with below configuration
const cors = require('cors');
app.use(cors())
Please let me know if works for you or not.
See the Github repo for more info: https://github.com/expressjs/cors
We can use npm package to enable this too
npm install --save cors
After package is in place, use it as middleware as follows.
var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors());
If you have requirement to confine your resource access to single application, that can be done as following
app.use(cors({
origin: 'http://yourapp.com'
}));
If you have requirement to add access to multiple applications, that can be done as follows
var allowedOrigins = ['http://localhost:3000',
'http://yourapp.com'];
app.use(cors({
origin: function(origin, callback){
// allow requests with no origin
// (like mobile apps or curl requests)
if(!origin) return callback(null, true);
if(allowedOrigins.indexOf(origin) === -1){
var msg = 'The CORS policy for this site does not ' +
'allow access from the specified Origin.';
return callback(new Error(msg), false);
}
return callback(null, true);
}
}));
Did you write middleware that attaches header before the line of code that handles PUT request? I have a similar code but it worked for me.
Another approach is to use npm 'cors' module.
For testing purpose, you can attach below test (you can attach the specific headers/methods later):
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', '*');
res.header('Access-Control-Allow-Methods', '*');
I am deploying a simple node server and a React app to Netlify. The React App makes an API request to the server, and uses cors via const cors = require("cors"); in version 2.8.5.
At first I specified the following (server.js)
app.use(
cors({
origin: CLIENT_ORIGIN
})
);
which only seems to tell the server "I am using CORS," but does not specifically set any headers or permit any whitelisted websites to access the server. I then set the CLIENT_ORIGIN in a .env file in my dev environment, and via the Build environment variables on Netlify. I deployed a new built for both the server and front-end, however I must have gotten it wrong somewhere:
Access to fetch at 'https://serverUrl.com/example/get' from origin
'https://react-app-example.com' has been blocked by CORS policy: No 'Access-
Control-Allow-Origin' header is present on the requested resource. If an
opaque response serves your needs, set the request's mode to 'no-cors' to
fetch the resource with CORS disabled.
I then tried setting:
app.use(function(req, res, next) {
res.header(
"Access-Control-Allow-Origin",
"https://react-app-example.com"
);
res.header("Access-Control-Allow-Headers", "Content-Type,Authorization");
res.header("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,DELETE");
if (req.method === "OPTIONS") {
return res.sendStatus(204);
}
next();
});
which also did not work. The error message remained the same. The thing that irks me is that I have a similar from from a few months ago which is built very similarly, but stays on heroku. The same methods as described above work without problem.
What am I missing?
After trying various things I finally arrived at the fact that Netlify does not support Node apps by itself (without extra tedious config).
The closest solution can be found here in another answer or via another service like Heroku.
The major issue I have with heroku is that when the dyno (in my case the server providing API routes) doesn't get called for a while it goes to sleep to save resources, and in turn takes a whole lot longer to respond on the first call. Have not found any other free solution for node/express apps that serve API routes, yet.
UPDATE: Heroku and Netlify don't play along nicely unless you add the following CORS parameters to the backend:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", CLIENT_ORIGIN);
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
res.header("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,DELETE");
res.header("Access-Control-Allow-Credentials", true); <--- this is the only different line I added.
if (req.method === "OPTIONS") {
return res.sendStatus(204);
}
next();
});
And then the following to the front end request via fetch:
fetch(`${API_BASE_URL}/dept/get/`, {
method: 'GET',
credentials: 'include', <-- this is the most important change
})
.then((res) => {...}
I have two URLs on the same server, mydomain.com and api.mydomain.com
Now in my API I have added the following to deal with access-origin:
app.use(function (req, res, next) {
// CORS headers
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header("Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, x-access-token, Cache-Control, Pragma"
);
next();
});
However when ever I attempt to make a request to this API I get the following error:
XMLHttpRequest cannot load https://api.mydomain.dk/login. Response to
preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'https://www.mydomain.dk' is therefore not allowed
access.
What am I missing?
The order is important, you have to do it before your routes :
Example Code :
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.get('/', function(req, res, next) {
// Handle the get for this route
});
app.post('/', function(req, res, next) {
// Handle the post for this route
});
I suggest using the cors express module.
EDIT :
Enable Cors Nodejs Apache
Enabling CORS on apache is a two-step process. First you must create a
file with the name .htaccess and add it to the directory where your
cross-domain-friendly files are. We recommend you create a new
directory for this. The file must contain the following code, (lines 2
and 3 may be optional):
Header always set Access-Control-Allow-Origin "*" Header set
Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header set Access-Control-Allow-Methods "PUT, GET, POST, DELETE,
OPTIONS"
The second step in the process is to enable .htaccess files. Test out
the CORS requests and see if they are already working (some
installations of Apache come with .htaccess files already enabled). In
order to test if it’s working, reload apache (using the command below)
and then fire your ajax request at your server.
sudo service apache2 restart
If that worked, you’re done. If not, then you need to add the
following code inside the VirtualHosts section of your
000-default.conf in your /etc/apache2/sites-available folder:
Options Indexes FollowSymLinks MultiViews
AllowOverride All Order allow,deny allow from all
Make sure you replace the /var/www/ with the actual path to your
document root. Congrats! You’re done!
I am trying to understand the cooperation of Angular and Node.js on the backend. I can't figure out however, how to use REST for data transfer between the two.
I have:
Node.js backend running on port 8000, responding to various GET and POST requests (via cURL).
Angular frontend is loaded through Apache, running on port 80.
Naturally, the JavaScript console identifies it as not allowed by Access-Control-Allow-Origin.
How is this commonly solved? Am I doing it wrong? Should I not run the frontend through Apache?
One way to solve it is using Cross-origin Resource Sharing. Browser support is decent as well.
You can also do it using cors
npm install cors
const cors = require('cors');
app.use(cors({
origin: 'http://example.com'
}));
http://example.com is your application origin/domain at front-end side.
Add this to your Node.js API server
server.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'OPTIONS,GET,POST,PUT,DELETE');
res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
if ('OPTIONS' == req.method) {
return res.send(200);
}
next();
});