How to resolve CORS issue in Angular 12?

I am working on an Angular project and I have login page and during submitting login API, I am facing CORS error. I am attaching screenshot of it also. Any suggestion would be appreciated.

 API Service.ts:

           constructor( private http: HttpClient ) { }
              httpOptionsPost = {
                headers: new HttpHeaders({
                  'Content-Type': 'application/json',
                  'Access-Control-Allow-Origin': '*',
                  'Access-Control-Allow-Credentials': 'true',
                  'Access-Control-Allow-Methods' : 'GET, POST, OPTIONS',
                  'Access-Control-Allow-Headers' : 'Origin, Content-Type, Accept, X-Custom-Header, Upgrade-Insecure-Requests',
                })
              };
        
              httpOptionsGet = {
                headers: new HttpHeaders({
                  'Content-Type': 'application/json',
                  'Access-Control-Allow-Origin': '*',
                })
              };
        
              _login(username, password) {
                const url = this.domain + '/api/login?username='+username+'&password='+password;
                return this.http.post(url, {}, this.httpOptionsPost);
              }

Login Component: 

    this.apiService._login(data.username, data.password).subscribe((resp: any) => {
          const resobj = JSON.parse(JSON.stringify(resp));
          console.log(resobj);
    })



Solution:

You need to set up proxy configuration for running the app locally.

A short example is:

// create a file proxy.config.json
{
  "/api": {
    "target": "http://example.com/", // put your actual domain
    "secure": false // true or false depending on your needs.
  }
}

Then run your project passing the proxy conf to ng-serve or configure it in the package.json. For instance:

ng serve --proxy-config proxy.conf.json

or

npm start -- --proxy-config proxy.conf.json

Or simply configure it in the angular.json.

Then, in your code, remove the usage of the domain, or assign the domain to localhost using environment.dev.ts if the domain is not the same as where you are going to deploy you app. I'm referring to the domain variable in this block.

_login(username, password) {
    const url = this.domain + '/api/login?username='+username+'&password='+password;
    return this.http.post(url, {}, this.httpOptionsPost);
}

Comments

Popular posts from this blog

Is there a compatibility list for Angular / Angular-CLI and Node.js?

Error when trying to inject a service into an angular component "EXCEPTION: Can't resolve all parameters for component", why?