Im doing an API with NestJS but I had an issue with the CORS, at first it didnt take the list of allowed domains and it allowed requests from any domain, so I implement this code to verify the origin and it works
options = {
origin: function (origin, callback) {
if (whitelist.indexOf(origin) !== -1) {
callback(null, true);
} else {
myLogger.error(`Request not allowed by CORS`)
callback(new Error('Not allowed by CORS'));
}
},
methods: 'GET',
}
app.enableCors(options);
But this issue happens too with the methods inside the CORS, it allows to make any type of request and it ignores the configuration that I set. I tried to implement the same origin function on the method but it didnt work.
If anyone has a solution and/or experienced the same problem, I'd really appreciate it if you let me know. Thank you
CodePudding user response:
My guess is that it's allowing you to make any request because you are not making a Preflight Request; these types of requests are executed by the browser automatically.
Before every request, these execute an OPTION
request, if it meets the conditions you defined in your options, your request will be executed, otherwise, you will get a CORS error.
If you are using something like Postman or Insomnia to make a request of any type, it will always allow you, because it's a simple request.
In short, if you want to test if your configuration for methods
is working, you only need to make a request of type OPTION
and it should return, in the header Access-Control-Allow-Methods
, the list of methods you defined.
About the origin function, have in mind that you will need to send the header Origin
in your request otherwise it will be undefined
.
And, if you don't want to allow the current origin you need to return false instead of throwing an error
myLogger.error(`Request not allowed by CORS`)
callback(null, false);
CodePudding user response:
Something like this might be what you are looking for. This would be in your main.ts
app.use(function (err, req, res, next) {
//replace with proper error
if (err.code !== 'CORERR') return next(err);
if (whitelist.indexOf(req.originalUrl) !== -1) {
next();
} else {
myLogger.error(`Request not allowed by CORS`)
next(err);
}
});