0
votes

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 on your server or proxy the request through another server.Alexander Staroselsky
That information does not matter. The API/server running at http://localhost:8191/api/, have you enabled CORS on that API/server?Alexander Staroselsky
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="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 itTiberiu Corneanu

1 Answers

0
votes

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/',...)