I have a nodeJS project on running on my virtual machine server , the point of this backend project is that it will provide some API for a script that will injected on different websites and will some HTML code in it.
I have surfed all the websites for cors error but could not find a solution to my problem.
I have set the headers on my back end project
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', '*');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
res.setHeader('Access-Control-Allow-Credentials', "true");
// Pass to next layer of middleware
next();
});
The node Js project is hosted on a domain and configured with nginx
P.s I have other node js projects running in that server and hosted on the same domain with the same configuration system in nginx but they are working perfectly fine , the problem is only in this new project.
What am I missing?
As you can see here I am trying to fetch an api from my node js project inside a browser example https://www.test.domain.com/api/TESTAPI but is it throwing the cors error
Also when sending the request this is the response headers I am getting
---------------Response Headers-----------------
[Object: null prototype] { 'x-powered-by': 'Express' }
CodePudding user response:
Your Access-Control-Allow-Headers should also include all the headers you try to set as well. Such as Access-Control-Allow-Origin , Access-Control-Allow-Methods and Access-Control-Allow-Credentials.
Example:
res.setHeader(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Authorization, Access-Control-Allow-Origin, Access-Control-Allow-Methods,Access-Control-Allow-Credentials"
);
Edit:
If you set Access-Control-Allow-Credentials to true, you cannnot set * for Access-Control-Allow-Origin
CodePudding user response:
This may not be a CORS error. This could be Chrome unable to load the webpage for some reason and telling you it's a CORS error. I would look through the rest of my app's load process and see if there was a hitch somewhere in it.
Per my answer here: CORS not working in Django but settings seem correct

