简体   繁体   中英

Basic Authentication Angular2 (Not CORS)

I am currently trying to call a jersey REST API that I have running locally on localhost:8080 through Angular 4 using HttpClient .

My Code: ```

ngOnInit() {
    const headers = new HttpHeaders();
    headers.append('Authorization', 'Basic ' + btoa('username:password'));
    headers.append('Content-Type', 'application/json');

    this.http.get('http://localhost:8080/mycall?myparam=myvalue', {headers: headers}).subscribe(data => {
      console.log(data);
    });
  }

```

When I make this call I get a 401 error saying that I am Unauthorized . However, when I run this through postman it goes through just fine. What am I doing wrong here?

NOTE : this is not a CORS issue, I am currently allowing CORS through an extension on firefox

HttpHeaders are immutable, so you need to do something like that

ngOnInit() {
    const headers = new HttpHeaders()
    .append('Authorization', 'Basic ' + btoa('username:password'))
    .append('Content-Type', 'application/json');

    this.http.get('http://localhost:8080/mycall?myparam=myvalue', {headers: headers}).subscribe(data => {
      console.log(data);
    });
  }

Actually you should not need the Content-type here for a GET request

I think the issue is that you haven't passed in your custom request headers to HttpClient , which is causing the unauthorised error.

Please try something like this.

const headers = new HttpHeaders();
headers.append('Authorization', 'Basic ' + btoa('username:password'));
headers.append('Content-Type', 'application/json');
const options = new RequestOptions({headers: headers});

this.http.get('http://localhost:8080/mycall?myparam=myvalue', options ).subscribe(data => {
  console.log(data);
});

You can simply pass in your RequestOptions to http.get as it does accept headers as an optional parameter. Please check following link for more details on the usage.

https://angular.io/api/common/http/HttpClient#get

Also, remember to import RequestOptions as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM