Angular 5使用基本身份验证获取/发布http

时间:2018-06-16 13:34:23

标签: angular api ionic-framework https

我有以下代码在没有身份验证的情况下进行获取http调用,一切正常。

let headers2 = {' Content-Type':' application / json'};   his.http.get(' https://api.test.com/account/get/',headers2).map(res => res.json())。subscribe(data => {           this.posts = data;});

但我不知道如何添加上述基本身份验证,如此(在curl中),但在离子身上:

curl --user admin:password -s -X GET" https://api.test.com/account/get/" -H" content-type:application / json"

无论我尝试了什么,都会遇到401身份验证错误。

谢谢

2 个答案:

答案 0 :(得分:1)

您可以在标题中附加基本授权,如下所示:

var headers_object = new HttpHeaders();
headers_object.append('Content-Type', 'application/json');
headers_object.append("Authorization", "Basic " + btoa("admin:password"));

const httpOptions = {
  headers: headers_object
};

答案 1 :(得分:0)

我收到401错误...我用过:

let headers = new Headers(); headers.append('授权','基本'+ btoa('admin:密码'));

headers.append('Access-Control-Allow-Headers','Content-Type');

headers.append('Access-Control-Allow-Origin','*');

headers.append('Access-Control-Allow-Methods','GET,PUT,POST,DELETE,PATCH,OPTIONS')

let options = new RequestOptions({headers:headers}); this.http.get('https://api.test.com/account/get/',options).map(res => res.json())。subscribe(data => {   ....

结果......

请求网址:https://api.test.com/account/get 请求方法:选项 状态码:401未经授权 远程地址:75.127.10.64:443 推荐人政策:no-referrer-when-downgrade 连接:保持活力 内容长度:590 内容类型:text / html 日期:星期六,2018年6月16日19:02:06 GMT Keep-Alive:超时= 10 服务器:nginx WWW-Authenticate:Basic realm =“Protected” 接受: / Accept-Encoding:gzip,deflate,br Accept-Language:en-GB,en-US; q = 0.9,en; q = 0.8 Access-Control-Request-Headers:access-control-allow-headers,access-control-allow-methods,access-control-allow-origin,authorization 访问控制请求方法:GET 连接:保持活力 主持人:api.test.com 来源:http://localhost:8100 用户代理:Mozilla / 5.0(Macintosh; Intel Mac OS X 10_13_4)AppleWebKit / 537.36(KHTML,与Gecko一样)Chrome / 66.0.3359.181 Safari / 537.36

相关问题