Uisng Angula2 JS无法打到外部服务?

时间:2018-05-13 11:27:05

标签: angular

从angular 2 JS调用我的marklogic服务器时,我收到了401 aunauthorized问题。

以下是我正在使用的代码段:

getPolicies() {
let username: string = 'admin';
let password: string = 'admin';
let httpHeaders = new HttpHeaders();

httpHeaders.set("Authorization", ("Bearer " + btoa(username + ":" + password)));
httpHeaders.set('Access-Control-Allow-Origin', "*");
httpHeaders.set('Access-Control-Allow-Credentials', 'true');
httpHeaders.set("Content-Type", "application/x-www-form-urlencoded");


this.http.get(this.serverUrl, { 
  headers: httpHeaders
}).toPromise() 
        .then(policy => console.log("policy values:"+ policy))
        .catch(err => console.log("error value:"+ JSON.stringify(err, null, 2)));

} enter image description here

可以在附加的屏幕截图中引用错误。能帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

您的发送未获得服务器授权的访问令牌

httpHeaders.set("Authorization", ("Bearer " + btoa(username + ":" + password)));

如果它有帮助,您也可以尝试这样的事情: 尝试在登录期间获取访问令牌并发送。

let headers = new HttpHeaders({ 'Authorization': 'Bearer ' + currentUser.access_token});