Angular 6 HTTP Get request with HTTP-Basic authentication

后端 未结 2 759
情书的邮戳
情书的邮戳 2020-12-17 16:43

I`m trying to access a URL with Basic Authentication.

The URL returns JSON data.

How can I add my username and password to this http request below?

相关标签:
2条回答
  • 2020-12-17 17:17

    Refer to https://angular.io/guide/http or https://v6.angular.io/guide/http#adding-headers

    import { HttpHeaders } from '@angular/common/http';
    
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type':  'application/json',
        'Authorization': 'Basic ' + btoa('username:password')
      })
    };
    

    Then use the headers:

    return this.http.get<AObjects[]>(this.postsURL, httpOptions); 
    
    0 讨论(0)
  • 2020-12-17 17:33

    i don't know what you want to do exactly after getting authorized, but to get authorized using a simple call with basic authentication you need to do like this:

    let authorizationData = 'Basic ' + btoa(username + ':' + password);
    
    const headerOptions = {
        headers: new HttpHeaders({
            'Content-Type':  'application/json',
            'Authorization': authorizationData
        })
    };
    
    this.http
        .get('{{url}}', { headers: headerOptions })
        .subscribe(
            data => { // json data
                console.log('Success: ', data);
            },
            error => {
                console.log('Error: ', error);
            });
    
    0 讨论(0)
提交回复
热议问题