0

I'm trying to make an external API request on GET method on an Angular app. But I have this error and nothing works: Access to XMLHttpRequest at 'https://xxxxxxx' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. How can I do to make the call on the server side (NodeJS)?

AppComponent.ts

  title = 'apis_calls';

  apiRoot: string = "https://1.ocs.oc-test.com";
  

  constructor(private http: HttpClient) {

    //let entireRequest = '';
    var bodyData = new FormData();
    let username = 'xxxxxx_Client';
    let password = 'xxxxxxx';


    //Headers parameters
    const header = new HttpHeaders();
    header.append('Content-Type', 'application/x-www-form-urlencoded');
    header.append('Accept', 'application/json');
    header.append('x-app-key', '0e5fdb7a-e808-4ea1-9577-2eeaa3719443');
    header.append('Access-Control-Allow-Origin', '*');
    header.append('Access-Control-Allow-Headers', 'application/x-www-form-urlencoded');
    header.append('Access-Control-Allow-Methods', 'GET,POST,OPTIONS,DELETE,PUT');
    header.append('Authorization', `Basic ${btoa(username)}:${btoa(password)}`);

    //Body parameters
  
    //bodyData.append('username', 'xxxxxxx');
    //bodyData.append('password', 'xxxxxxxxx');

        
    const myInit = {
      method: 'POST',
      headers: header,
      mode: 'cors',
      body: JSON.stringify({
          'username': username,
          'password': password
      })
  }



    alert('API had been called.');
    console.log("HEADERS", header);
    this.http.post('https://ocrs.com', myInit, {
    }).subscribe(data => {
      console.log('MY INIT', myInit);
      console.log(data);
    })
    console.log('NOT WORKING');
  }
}```




  • Mmh not really.. How can I do to create the create the nodejs file and create the communication with my frontend? But thank you very much for the link ;) – Julien Ferrier Feb 17 '22 at 20:10
  • CORS needs to be solved with response headers from the server. Adding them to the Angular request only makes the situation worse (and won’t solve a thing). You need useCors on the nodejs side (if you use express) – MikeOne Feb 17 '22 at 20:30

0 Answers0