Can someone help me please, I have a problem in CORS policy and I have no access to the backend of the site.
This is the code I use in the backend (node.js):
app.use(cors({
Access_Control_Allow_Origin: "*",
origin:"*",
methode:['GET','POST','PATCH','DELETE','PUT'],
allowedHeaders:'Content-Type, Authorization, Origin, X-Requested-With, Accept'
}));
this is the code of the front end (I used Angular 13) to import API: environment.ts
export const environment = {
production: false,
serverURL: 'http://localhost:3000/api/'
};
I've tried also this code but it didn't work:
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');
// 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', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
Make sure you have the right imports:
and either use:
Or change your code to this:
Be careful with '*' as Access-Control-Allow-Origin in production. Change this back only to the clients that are allowed to connect to your API.
If that didn't help, then try to set proxy requests to enable CORS in Angular: Inside the src folder of your application, create a new file called
proxy.conf.json
. This is a JSON file that will contain the configuration for the proxy server. Here, we'll tell our Angular application to act as another server that takes API calls and diverts them to http://localhost:3000.Inside the proxy.conf.json file, add the following code:
Next, inform Angular about this proxy configuration. We can do that by adding a proxyConfig option inside our angular.json file: