Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 7 app getting CORS error from angular client

I have developed an angular 7 app with express backend. Express running on localhost:3000 and angular client is running on localhost:4200.

In the server.js I have (not the entire code)

const app = express();
// Enable CORS
app.use(cors());
// Get our API routes
const api = require('./api');
// Set our api routes
app.use('/api', api);
app.use(express.static(__dirname + '/dist/sfdc-event'));

In the api.js file, I have router.get(‘/oauth2/login’) which redirects to https://example.com which sends an access token and authenticates the user (OAuth2 authentication).

When I am calling the url http://localhost:3000/api/oauth2/login everything is working fine, but when I am trying to do the same from angular component.ts -> service.ts I am getting the following error.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource Reason: CORS header ‘Access-Control-Allow-Origin’ missing

Angular app flow as follows login.component.ts which has a button calling a service api.service.ts which executes a http get.

login.component.ts

sfdcLogin(): void {
  console.log('DEBUG: LoginComponent: ', 'Login button clicked..');
 this.apiService.login().subscribe( data => { console.log( data ); });
}

api.service.ts

login() {
  console.log('DEBUG: APiService login(): ', 'login() function.');
  const URL = 'oauth2/login';
  console.log('DEBUG: ApiService login URL : ', `${environment.baseUrl}/${URL}`.toString());
  return this.http.get(`${environment.baseUrl}/${URL}`)
    .pipe( map( res => res ));
}

Can someone help me get past the error? I have a) CORS b) serving static files from server.js as

app.use(express.static(__dirname + '/dist/sfdc-event'));

c) dynamic environment variable. What else I am missing?

like image 999
Arup Sarkar Avatar asked Nov 26 '18 01:11

Arup Sarkar


People also ask

How do you fix the CORS issue in angular 7?

CORS error due to browser's same origin policy. To get around this, you need to tell your browser to enable your client and your server to share resources while being of different origins. In other words, you need to enable cross-origin resource sharing or CORS in your application.

What is CORS issue in angular?

CORS is an HTTP header- based mechanism that allows the server to indicate any other domain, scheme, or port origins and enables them to be loaded.

How do you implement CORS in Angular js 7?

Since, your angular app is running on 4200 port and backend running on 3000 port, the origin of both the application is different. To solve this problem, you can setup "nginx" in your machine. This will make all your requests from angular and backend, go via "nginx" server. Thus, solving the problem of CORS.

How to fix Cors issues in angular apps?

When it comes to fixing CORS issues in an Angular app, we can go about the problem in two different ways: We can get around CORS issues using proxies provided by Webpack. First things first, open up your Angular project and create a new file in your src directory called proxy.conf.json, with the following contents:

How to set up a proxy in Angular without Cors issues?

You can find the list of available options on their official documentation. Next, you need to make Angular aware of your proxy configuration, by pointing Angular to this file through your angular.json, using a proxyConfig key: Finally, with the configurations in place, now you should be able to serve your app without having CORS issues.

How to fix angular CLI not responding to Cors header?

One way to fix it is by enabling proper CORS headers request on the server-side. Another way is to configure Angular CLI proxy. Note: The correct approach or solution is to configure the backend server, but that may not always be feasible.

Why can't I see the response to my angular request?

This should open our Angular application in the browser. Visit http://localhost:8000 in your browser, and check the console. You'll find a CORS error thrown by the browser. CORS error in Angular. Also, the browser has blocked your request, and you won't be able to see the response of the request.


2 Answers

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

like image 135
piotr szybicki Avatar answered Sep 24 '22 13:09

piotr szybicki


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!

like image 34
Freestyle09 Avatar answered Sep 24 '22 13:09

Freestyle09