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.
Related
I've been developping a website using express(NodeJS) for the backend and React for the frontend. I've come accross the issue where my application won't work on Firefox due to this error "ReferenceError: SharedArrayBuffer is not defined".
After having searched a bit online, it appears it has to do with CORS. I saw that on Chrome there is a warning about the use of SharedArrayBuffer as well.
So I read that I need to set those headers
Ì€Cross-Origin-Opener-Policy: same-origin Cross-Origin-Embedder-Policy: require-corp
But I am not sure on how to do that. On my backend I've been using the cors package to set my cors headers and options as such
const corsOptions = {
origin: process.env.CLIENT_URL,
credentials: true,
'allowedHeaders': ['sessionId', 'Content-Type'],
'exposedHeaders': ['sessionId'],
'methods': 'GET,HEAD,PUT,PATCH,POST,DELETE',
'preflightContinue': false
}
app.use(cors(corsOptions));
I've also tried using this method but it doesn't appear to work either :
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content, Accept, Content-Type, Authorization');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
res.setHeader('Cross-origin-Embedder-Policy', 'require-corp');
res.setHeader('Cross-origin-Opener-Policy','same-origin');
next();
});
Am I totally missing something/misunderstanding?
It is my first time developping a web application and I am kind of lost at this point. Any help would be grately appreciated.
Thank you
Not sure what causes this, but for me using a different route worked
Cross-origin isolation using node / express
app.use(function(req, res, next) {
res.header("Cross-Origin-Embedder-Policy", "require-corp");
res.header("Cross-Origin-Opener-Policy", "same-origin");
next();
});
app.get('/', async (req, res) => {
res.sendFile(path.join(__dirname, 'public/index.html'));
});
// does **not** work, no cors headers in response
app.get('/app', async (req, res) => {
res.sendFile(path.join(__dirname, 'public/index.html'));
});
// does work, cors headers in response as expected
try to process options request in your custom middleware
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content, Accept, Content-Type, Authorization');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
res.setHeader('Cross-origin-Embedder-Policy', 'require-corp');
res.setHeader('Cross-origin-Opener-Policy','same-origin');
if (req.method === 'OPTIONS') {
res.sendStatus(200)
} else {
next()
}
});
The Cross-Origin-Embedder-Policy and Cross-Origin-Opener-Policy must be set on the client website (client.example.com), i.e. the one consuming the backend resources.
The backend (api.example.com) should be setup to allow for CORS (for example using the cors package as you are) from the client's origin.
Access-Control-Allow-Origin: client.example.com
If you are embedding images or link from the backend, then you would need to add the crossorigin="anonymous" attribute.
<img src="api.example.com/image.png" crossorigin="anonymous" alt="" />
If you are embedding an iframe, then the target of the iframe would need to add the Cross-Origin-Resource-Policy: cross-origin and Cross-Origin-Embedder-Policy: require-corp headers on the backend (api.example.com) to allow other websites to embed from that resource. Note that this means anyone would be able to embed from your backend.
Note that I am not sure how this relates to the SharedArrayBuffer exception you are seeing.
I have below code which is working fine for GET and POST but not for PUT in node js. I am using method overloading for GET and PUT.
const AuthRoutes = Router();
const AppRoutes = Router();
AuthRoutes.get('/customer/:customername', getCustomerbyname);
AuthRoutes.post('/calculate/:id', calculate);
AuthRoutes.put('/customer/:customername', saveCustomer);```
Here my GET and POST is working fine but for PUT its giving me error. Below URL I am trying for PUT.
https://domainname/customer/abc
I dont know what I am missing here.
Error - You don't have permission to access /domainname/customer/abc
Can you please help me if I am missing something here. Basically I am trying to do a PUT request by providing customer name in URL and other details in BODY section of request. So if customer with name exist, it will update it otherwise create it newly. Am I missing any npm package here?
Try this:
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");
res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
next();
});
I took it from here :
Response
I'm using Angular 8 and ExpressJS. Everything work perfectly, the app is live and a lot of users (6000) are using it. But there are a few users (less than 10) that get Unknown Error (code 0) from any API call.
This is the error response:
{"headers":{"normalizedNames":{},"lazyUpdate":null,"headers":{}},"status":0,"statusText":"Unknown Error","url":"https:/xxxxxxxxxx/api/auth/recover-pass","ok":false,"name":"HttpErrorResponse","message":"Http failure response for https://xxxxxxxx/api/auth/recover-pass: 0 Unknown Error","error":{"isTrusted":true}}
I readed it can be an CORS error, but I don't think so. I'm using this
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Methods", "POST, PUT, OPTIONS, DELETE, GET");
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, x-access-token");
res.header("Access-Control-Allow-Credentials", true);
next();
});
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.
While reading some tutorial I found that
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'DELETE, PUT');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
What does every res.header mean? and what are their functions?
These headers allow cross-domain access: https://ru.wikipedia.org/wiki/Cross-origin_resource_sharing
Without these headers client scripts are allowed to get data from your server (edited: in your case you specify request types DELETE and PUT) only if their origin is the same (i.e. your client-side html and javascript are loaded from the same domain name). Scripts from different domains will receive an error like 'this origin is not allowed' or something like that.