Angular 7 app getting CORS error from angular client
For Angular 7 you must do other implementation. From angular documentation you must create a proxy.js file:
https://angular.io/guide/build#using-corporate-proxy
Edit the path for your own backend server.
proxy.js:
var HttpsProxyAgent = require('https-proxy-agent');var proxyConfig = [{ context: '/api', target: 'http://your-remote-server.com:3000', secure: false}];function setupForCorporateProxy(proxyConfig) { var proxyServer = process.env.http_proxy || process.env.HTTP_PROXY; if (proxyServer) { var agent = new HttpsProxyAgent(proxyServer); console.log('Using corporate proxy server: ' + proxyServer); proxyConfig.forEach(function(entry) { entry.agent = agent; }); } return proxyConfig;}module.exports = setupForCorporateProxy(proxyConfig);
Later add this to your package.json
"start": "ng serve --proxy-config proxy.js"
And call this with:
npm start
And in your app.js just simply add:
const cors = require("cors");app.use(cors());
I had same problem and that solved my issue. I hope it helps!
If this is just for development I recommend using proxy that comes with angular-cli.Create a file called proxy.json
and
{ "/api/oauth2/login": { "target": "http://localhost:3000/api/oauth2/login", "secure": false }}
and the call ng serve --proxy-config proxy.json
. If you expect this to be still a problem in production then we have to have a bigger conversation.
Full documentation:https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/proxy.md
Also what is CORS exacly: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
To divert all calls for http://localhost:4200/api
to a server running on http://localhost:3000/api
, take the following steps.
Create a file
proxy.conf.json
in the projectssrc/
folder, next topackage.json
.Add the following content to the new proxy file:
{ "/api": { "target": "`http://localhost:3000`", "secure": false }}
- In the CLI configuration file, angular.json, add the proxyConfig option to the serve target:
..."architect": { "serve": { "builder": "@angular-devkit/build-angular:dev-server", "options": { "browserTarget": "your-application-name:build", "proxyConfig": "src/proxy.conf.json" }, ... }}...
- To run the dev server with this proxy configuration, call
ng serve
.