typescript 使用 HTTP-Basic 身份验证的 Angular 6 HTTP Get 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/53613529/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:43:43  来源:igfitidea点击:

Angular 6 HTTP Get request with HTTP-Basic authentication

javascriptjsonangulartypescriptrest

提问by YupYup

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

我正在尝试使用基本身份验证访问 URL 。

The URL returns JSON data.

URL 返回 JSON 数据。

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

如何将我的用户名和密码添加到下面的这个 http 请求中?

private postsURL = "https://jsonExample/posts";

getPosts(): Observable<AObjects []>{
    return this.http.get<AObjects[]>(this.postsURL); 
}

回答by Daniel W.

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

参考https://angular.io/guide/httphttps://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); 

回答by Mohammad Kh

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);
        });