Angular 7 app getting CORS error from angular client

Discussão em 'Angular' iniciado por Arup Sarkar, Janeiro 6, 2025.

  1. Arup Sarkar

    Arup Sarkar Guest

    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?

    Continue reading...

Compartilhe esta Página