Reputation: 1092
On an Angular 7 project, using HttpClient, I have this simple line of code on a click button handler:
this.http
.get('http://localhost:30123/api/identity/name/' + this.name)
.subscribe((answer: Identity[]) => {
this.identities = answer; // debug does not get here...
});
that's throwing this error at the Console Debug tab on VSCode:
Access to XMLHttpRequest at 'https://dihgldata.ingeniusds.cat/api/identitat/nom/montilla' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
[http://localhost:4200/] core.js:15724 {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "https://dihgldata.cat/api/identitat/nom…", ok: false, …}
but...
I'm using three different tools to test the same URL and getting a correct response from the api.
First: Postman.
(Well, you know: headers, CONTENT-TYPE,... are diferent when sent from this utility than from chrome)
Second: VS Code Extension Rest Client.
(As per Postman, these utilities are useful to test the API but doesn't help with errors at the client side code)
Third: Chrome DevTools.
Here is my big deal. I went to Network tab on Chrome DevTools and I can see the response of the API just before it's been treated by my code and there is the full response with a OK-200 Status.
No errors at Console tab on Chrome DevTools.
Using VS Code integrated debugger with Chrome Extension tracing never gets to the line where the answer is assigned to the local variable and the error is shown in VSCode Debug Console with no other clue.
EDIT
Tried the same URL as on Angular HttpClient on Chrome address bar and the response from the same API is shown correctly.
Upvotes: 1
Views: 4514
Reputation: 36
When you doing request to http://localhost:30123/ from any another url it will be blocked by CORS(Cross-Origin Resource Sharing) politics of http://localhost:30123/.
You have to allow CORS from any url or from only http://localhost:4200/.
In Java you can use CORS Filter. https://howtodoinjava.com/servlets/java-cors-filter-example/
Upvotes: 2