1

Hello i am creating an Angular application that i need to call an API. I have run into the CORS Error. "No Access-Control-Allow-Origin" which I have found a few things on line about but I still do not understand where I am supposed to add the middlewhere. I wonder if someone could be specific on how to get this to work with angular cli.

If you open a command prompt and type ng new test then open that test folder up and type npm start. you add the code to call an api lets say localhost/someapi/api/people but because you're not calling localhost:4200 you get this error.

So just so that my question is clear, I understand that you need to add the cors middle where on the server. But the question is, where in the angular 5 app do I add this for node to read it and allow this to work?

Below is the code that I'm using to call api.

getToken():void{
    let headers = new Headers({'Content-type': 'application/x-www-form-urlencoded'})

    let params = new URLSearchParams();
    params.append('username','some-username');
    params.append('password', 'some-encripted-password');
    params.append('grant_type', 'password');

    let options =  new RequestOptions();
    options.headers = headers;

    this.http
        .post(this.appConfig.baseRoute + 'token',params.toString(), options) 
        .subscribe(result=>{ });
  }
3xGuy
  • 2,235
  • 2
  • 29
  • 51

1 Answers1

0

CORS headers should be set in server-side as per the answer in the link that you provided. There shouldn't be anything to set on the Angular client side other than maybe authentication tokens if you server requires them.

To ease your development locally, you could set up a proxy for ng serve.

Add this file in your root (folder with angular-cli.json)

proxy.conf.js

const PROXY_CONFIG = [
  {
      context: [
          // what routes to proxy
          "/api",
      ],
      // your backend api server
      target: "http://localhost:8000",
      secure: false
  }
]

module.exports = PROXY_CONFIG;

instead of calling ng serve, use ng serve --proxy-config proxy.conf.js

Joshua Chan
  • 1,797
  • 8
  • 16