Search code examples
amazon-web-servicesaurelia

Adding a 'Access-Control-Allow-Origin' header in Aurelia


When I try to access my API via the Aurelia frontend I get the following error:

XMLHttpRequest cannot load https://[my aws API URL here]/auth. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access. The response had HTTP status code 403

This is my code:

 constructor(Aurelia, HttpClient) {

    HttpClient.configure(http => {
      http.withBaseUrl(config.baseUrl);
    });

    this.http = HttpClient;
    this.app = Aurelia;

    this.session = JSON.parse(localStorage[config.tokenName] || null);
  }

login(username, password) {

    var client = new HttpClient();
    client.createRequest(config.apiUrl + '/auth', { username, password })
      .asPost()
      .withHeader('Access-Control-Allow-Origin', '*')
      .withBaseUrl(config.baseUrl)
      .send()
      .then((response) => response.content)
      .then((session) => {
        localStorage[config.tokenName] = JSON.stringify(session);
        this.session = session;
        this.app.setRoot('app');
    });
  }

What am I doing wrong?

It works fine in Postman.


Solution

  • I fixed the problem by using the 'Enable CORS' in the AWS API gateway interface, and deploying the API again. Thanks for pointing me in the right direction!!