No 'Access-Control-Allow-Origin' header is present.. angular 7 and express - node.js

I am running a server with express at port 3000 and a client with angular 7 at port 4200. Once I make a request, I run into CORS issue.
Access to XMLHttpRequest at 'http://localhost:3000/drug' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I have tried all the solutions online like using cors package, and setting the middleware before router like below codes (Angular 6 - No 'Access-Control-Allow-Origin' header is present on the requested resource). But it still is not solved and keep getting same errors. Does anyone have same problem that CORS is not solved with all the solutions? Could you please help me?
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
res.header(
"Access-Control-Allow-Header",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
});
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "http://localhost:4200");
res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
res.header(
"Access-Control-Allow-Header",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
});

Put this line of code app.use(cors()); before routing code. (Assuming you have installed cors package).

I think answer would be so late, but for somebody in future:
You have to turn it on at the server side.
I'm .Net developer, therefore I'll show in example of .Net core app.
In startup file method ConfigureServices you should add next code
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.WithOrigins("http://localhost:4200")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
After that you should edit method Configure. Add next line before calling UseMvc
app.UseCors("CorsPolicy");
That's all. I hope this answer will help to somebody.

Related

CORS blocks only certain requests even if headers are configured

When I perform certain requests, I get this error :
Access to XMLHttpRequest at 'https://myApi/myRoute' from origin 'http://localhost:19006' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
but my app is configured like this :
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:19006");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header('Access-Control-Allow-Credentials', 'true');
next();
});
If I use this syntax I get the same problem :
app.use(cors({
origin: true, credentials: true
}));
How it is possible that certain requests like login etc .. are ok, but some other are not ?
I work on expo for a react native app in web browser version.

No 'Access-Control-Allow-Origin' header is present on the requested resource NodeJS API

I am using a Angular 2 app and a NodeJS API. When I had the API in localhost everything was working just right, but I published my NodeJS API to a real server and it gives me that error when I try to access to any method of the API:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource
I was checking some anwsers from another topics here in stackoverflow and nothing has worked for me.
I've this snipped :
app.use(require("cors")());
app.use(function(req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept,responseType"
);
res.setHeader(
"Access-Control-Allow-Methods",
"POST, GET, PATCH, DELETE, OPTIONS"
);
next();
});
So I have the "*" in Access-Control-Allow-Origin header why I got the error that I don't have this header in my headers?
Thanks in advance.
Use only the middleware
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
more details

Google Maps API, fetch method having CORS issue

As stated in the title of this question, i'm having CORS issues with a fetch method. Here are the solutions i've tried. Obviously none have worked.
Actual console error:
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:3000' is therefore not allowed
access. If an opaque response serves your needs, set the request's
mode to 'no-cors' to fetch the resource with CORS disabled.
I tried to fix the issue via my Express server. I am configuring this before I establish my routes.
import cors from 'cors';
app.use(cors({
origin: '*',
}));
Also tried it this way.
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();
});
Client side service. Set {mode: 'cors'} object.
fetch(requestUrl, {mode: 'cors'}).then((response) => {
return response.json();
}).then((restaurants) => {
resolve(restaurants);
}).catch((err) => {
reject(err);
});
At this point, i'm lost. I'm just trying to get data back from google maps api. Any help would be grateful.

CORS request not working when sending authorization headers

EDIT: Kevin B answered my question in a comment below. I added some logic to send a 200 request if an OPTIONS http request hit my API to fix the problem. Here is the code:
var allowCrossDomain = function(req, res, next) {
if ('OPTIONS' == req.method) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
res.send(200);
}
else {
next();
}
};
router.use(allowCrossDomain);
Original Question:
I currently am trying to get an Ionic 2 application running on my localhost to be able to send data to an Express 4 application. It works when I send requests without an authorization header. However, once I added auth headers, my API began to throw errors. I have done my research and have tried to implement what I found here: (https://stackoverflow.com/a/15254158/5379931.
However, I am getting errors still. If I set Access-Control-Allow-Origin like this:
res.header("Access-Control-Allow-Origin", "http://localhost:8100");
I get this error:
XMLHttpRequest cannot load URL. Response to preflight request doesn't pass
access control check: The 'Access-Control-Allow-Origin' header has a value
'http://localhost:8100/' that is not equal to the supplied origin. Origin
'http://localhost:8100' is therefore not allowed access.
If I set my Access-Control-Allow-Origin header like this:
res.header("Access-Control-Allow-Origin", "http://localhost:8100/");
I get this error:
XMLHttpRequest cannot load URL. No 'Access-Control-Allow-Origin' header is
present on the requested resource. Origin 'http://localhost:8100' is
therefore not allowed access. The response had HTTP status code 400.
Here is the rest of my express 4 code that is relevant:
router.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:8100");
res.header("Access-Control-Allow-Headers", "Origin, Authorization, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Credentials", true);
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
next();
});
It looks like you forgot to respond to the options request. By not responding, it will go to your error handler and be dealt with as if it were an error.
Just send a 200 status within your .use if it is an options request so that it doesn't reach your error handler.

CORS in Node.js and AngularJS

I have a CORS problem with my app.
My stack is Node.js with Express 4 and AngularJS using Restangular
I already have tried a few things (for example) but I keep getting:
XMLHttpRequest cannot load http://localhost:8080/api/users. Request header field Content-Type is not allowed by Access-Control-Allow-Headers.
In the server side I have this headers:
app.all('/*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods", "GET, POST","PUT");
next();
});
In the AngularJS part I am using this:
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
And I am doing the post with Restangular like this:
var baseUsers = Restangular.all('users');
....
....
baseUsers.post(newUser).then(function(user){
console.log(user);
});
One more thing, in the Node.js server I am consoling the req.method and it says OPTIONS, I really don't know why.
Perhaps is something silly, hope someone can help me.
Thanks!
Change -
res.header("Access-Control-Allow-Headers", "X-Requested-With");
TO
res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");
Source 1
Source 2
I am posting same answer with a detailed code, Because i got some issues when i use the selected answer.
Just pull the code below after initialization of the app object
app.all('/*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");
res.header("Access-Control-Allow-Methods", "GET, POST","PUT");
next();
});
I hope this will be little bit more helpful.

Resources