Hikaru Shindo
Hikaru Shindo

Reputation: 2913

Cannot call API from localhost:4200 - Angular

I'm working on an Angular project. I need to test API call from the Angular app but it's not working. It returns me error,

Access to XMLHttpRequest at 'http://...../api/v1/user/authen' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

On the Sever has already set Access-Control-Allow-Origin: '*'

I also made a simple html+Jquery file to test calling API and it works perfectly.

  function callApi(){
      $.ajax({
      type: "POST",
      url: 'http://..../api/v1/user/authen',
      data: {
        "user": "admin",
        "password": "123456"
      },
      success: function(data){
        console.log(data);
      },
    });
  }

But from the Angular APP I still got the error. Is there anything I need to specifically set on Angular app ?

Upvotes: 0

Views: 3956

Answers (2)

Hikaru Shindo
Hikaru Shindo

Reputation: 2913

I do not understand clearly but I solve it by adding JSON.stringify() to the payload.

  login(credential) : Observable<any> {
    return this.http.post<any>( 
    this.baseUrl + '/user/authen', JSON.stringify(credential)
    )
    .pipe( 
      map( res => res ),
      catchError( this.handleError )
    );
  }

Upvotes: 0

Rajkumar Soni
Rajkumar Soni

Reputation: 41

This might be a problem with the server itself, it's not allowing to access API form localhost:4200. You can run your app by disabling google chrome security and try to hit the API.

Open the Run in your windows machine and paste the link below for disabling web security and try to hit API.

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
--disable-web-security --user-data-dir="C:\tmpChromeSession"

Upvotes: 2

Related Questions