0

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 ?

4
  • 1
    The problem is probably on the server. Maybe the framework has missed the access control allow origin somehow. You should probably post the server code Commented Jun 26, 2020 at 9:59
  • we have to enable CORS from the api or the server side. This is not an issue with the angular code. Commented Jun 26, 2020 at 10:00
  • quick check - 1) are we calling the correct api? 2) in the chrome network tab for api, can we see Access-Control-Allow-Origin: '*' ? questions from my experience Commented Jun 26, 2020 at 10:03
  • What language you're using in back end? can you show us some back end code where you added Access-Control-Allow-Origin: '*'. Commented Jun 26, 2020 at 10:27

2 Answers 2

2

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" 
Sign up to request clarification or add additional context in comments.

4 Comments

Sorry, I'm using Macbook.
I haven't used in mac but you can try this in your Macbook. open -n -a /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --args --user-data-dir="/tmp/chrome_dev_test" --disable-web-security
If API works fine in disabled security mode then there is some problem in server site Allow access origin code.
Nice, It's works!
0

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 ) ); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.