Angular httpClient get response using authorization Bearer Unknown Error

Published

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

Source: Angular Questions

Published
Categorized as angular, jwt, node.js, typescript Tagged , , ,

Answers

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/’,…)


Ransom Barrows

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Still Have Questions?


Our dedicated development team is here for you!

We can help you find answers to your question for as low as 5$.

Contact Us
faq