Try to search your question here, if you can't find : Ask Any Question Now ?

Angular 7 app getting CORS error from angular client

HomeCategory: stackoverflowAngular 7 app getting CORS error from angular client
julie asked 2 weeks ago

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?

1 Answers
Best Answer
Amit answered 2 weeks ago
Your Answer

5 + 11 =

Popular Tags

WP Facebook Auto Publish Powered By : XYZScripts.com