0

Service.ts

public welcome(token: any){
    let tokenString = "Bearer "+token
    console.log("tokenString is: "+tokenString)
    let header = new  HttpHeaders().set("Authorization",tokenString);
    const requestOptions = {  headers: header};  
    return this.httpClient.get('http://localhost:8191/api/',{
      responseType: 'text' as 'json',
      headers: header
    });
  }

WebPage Console:

tokenString is: Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJqYXZhdGVjaGllIiwiZXhwIjoxNjIzMTMyNzc5LCJpYXQiOjE2MjMwOTY3Nzl9.h6aw8VBFHXWJQ5R2jRyn0MUqbe4rT3RvUCsELfcKHSU

Access to XMLHttpRequest at 'http://localhost:8191/api/' 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.

headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)} message: "Http failure response for http://localhost:8191/api/: 0 Unknown Error" name: "HttpErrorResponse" ok: false status: 0 statusText: "Unknown Error" url: "http://localhost:8191/api/"

Controller Postman request is working enter image description here

  • 1
    Looking at the message, the issue is that the server is not accepting the request because of CORS. You'd need to [enable CORS](https://enable-cors.org/) on your server or proxy the request through another server. – Alexander Staroselsky Jun 07 '21 at 20:26
  • That information does not matter. The API/server running at `http://localhost:8191/api/`, have you enabled CORS on that API/server? – Alexander Staroselsky Jun 07 '21 at 20:37
  • I already added @CrossOrigin(origins = "*") and I actually make a call to the controller where I send the credentials in order to receive the token and that is working because I see tokenString in console output. I tried to take your advise and I added @CrossOrigin(origins="http://localhost:4200/") above the method call but I still see the same error Angular CLI: 11.2.9; Node: 14.16.1; OS: win32 x64; Angular: 11.2.10 Sorry I was not able to edit it – Tiberiu Corneanu Jun 07 '21 at 20:56

1 Answers1

0

To solve the CORS problem, you have 2 approaches 1. Enable CORS on your server or 2. Proxy your request by creating a file named proxy.conf.json like this:

{
"/api": {
  "target": "http://localhost:8191/",
  "changeOrigin": true
}

}

And make the call like this this.httpClient.get('/api/',...)

Rasha Elsayed
  • 660
  • 1
  • 7
  • 22
  • Hello I tried that also and it's seams that it display the same think, so no change what so ever – Tiberiu Corneanu Jun 09 '21 at 12:07
  • The above configuration rewrites the url to http://localhost:4200/api/..., so it should solve the problem. For the borwser, it is as if you are accessing the same origin. Did you include the proxy.conf.json in your angular.json? check this answer https://stackoverflow.com/questions/47536466/cors-issue-with-proxy-conf-json-in-angular-app – Rasha Elsayed Jun 09 '21 at 13:42