Node origin even though headers are set - javascript

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!

Related

Enabling CORS with Express.js to allow multiple ports to communicate [duplicate]

This question already has an answer here:
CORS Error: “requests are only supported for protocol schemes: http…” etc
(1 answer)
Closed 2 years ago.
I'm trying to do API calls with React and Axios from my front end (localhost:3000) to my back end (localhost:4567), but I keep getting this error:
Access to XMLHttpRequest at 'localhost:4567' from origin 'http://localhost:3000' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
I have tried to allow CORS by adding this to my back end code, which uses express.js:
const cors = require("cors");
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "localhost:3000");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type,
Accept");
next();
});
But it does not seem to have made a difference. Any ideas on how to allow my API calls from one port to another?
//Enable CORS
app.use(function (req, res, next) {
let origin = req.headers.origin;
res.header("Access-Control-Allow-Origin", req.headers.host.indexOf("localhost") > -1 ? "http://localhost:3000" : origin);
res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
res.header('Access-Control-Allow-Credentials', true);
next();
});
Use above lines below the, var app = express();
Note - No need to use const cors = require("cors");
You can use $ npm install cors for that :
https://www.npmjs.com/package/cors#configuration-options

Express.js CORS configuration, PUT does not work?

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', '*');

How to fix CORS error with credentials: include?

Another question about CORS, I looked through a lot of information, but couldn't do anything. So I will be grateful for the help.
I am sending a fetch request with credentials enabled. What the browser regularly swears on at Access-Control-Allow-Credentials. I tried to configure a proxy, but it also does not work with it. So I need to add Access-Control-Allow-Credentials in response settings on the server. But I don't realize how.
I'm using create-react-app. There is not even a file with the familiar server code
error:
The value of the 'Access-Control-Allow-Credentials' header in the response is ''
which must be 'true' when the request's credentials mode is 'include'
Response headers:
access-control-allow-origin: http://localhost:3000
Request headers:
WARNING Provisional headers are shown
Access-Control-Request-Headers: access-control-allow-credentials,access-control-allow-origin
Access-Control-Request-Method: GET
Origin: http://localhost:3000
Referer: http://localhost:3000/
Hi use the following code in your server.js or app.js in node.
var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors());
app.all('*', function (req, res) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");```
If your backend is using Express, try to add this piece of code below:
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Credentials', true);
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept'
);
next();
});
Another solution, you can use cors module, just basically install it:
npm install cors --save
And add this code in your server:
var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors());
Since you're using create-react-app the easiest thing to do is to use a proxy so that the request looks like it is coming from the same domain and avoid CORS altogether. Assuming your backend server will be on the same host, this is actually closer to production as well.
Webpack has a clean way to do this. See this blog by facebook: https://facebook.github.io/create-react-app/docs/proxying-api-requests-in-development
This has gotten incredibly easy to do now. All you need to do is add a proxy field to your package.json. For example -
"proxy": "http://localhost:4000",

CORS on server header

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) => {...}

Access-Control-Allow-Origin in React JS on Meteor App

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

Categories

Resources