enable CORS via proxy configuration in ANGULAR
To enable CORS via proxy configuration, we need to generate a src/proxy.conf.json file inside the Angular root folder and also place the following code inside of it.
{
"/api/*": {
"target": "http://localhost:3000",
"secure": false,
"logLevel": "debug"
}
}
Define Proxy Configuration values in angular.json To register a proxy configuration, we need to go to the angular.json file and place the following code inside the serve/options. It will set the src/proxy.conf.json file in our Angular app.
"architect": {
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "project-name:build",
"proxyConfig": "src/proxy.conf.json"
},
}
}
Now, you are all set to start the dev server with the current proxy configuration, run the given below command. Please restart the server if you make any updates to your proxy conf file.
ng serve --open
Enable CORS in Node/Express Server Now, we will learn how to enable CORS in the Express and Node js app. We will look at one of the most straightforward methods to configure CORS in the express by using a third-party package.
You can run the following command to add the cors package in node/express backend.
npm install cors --save
Next, you can add the below code to enable cors in Express server.
// server.js
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
/* server configuration here */
Finally, CORS is enabled in the node server.
The Access-Control-Allow-Origin: * header will be rendered when any request is made to your application. This header chooses which origin are authorized to access the server resources with CORS.
Comments
Post a Comment