2015-07-28 71 views
5

我在Angularjs 1.3中拥有Java REST服务和消费者。服务基于JSON并期望BASIC身份验证(用户名 - 密码)。 在AgJs 1.3中,我使用Base64工厂代码(在谷歌上找到)从用户名和密码创建基本身份验证令牌,并且能够使用成功的服务。如何在Angularjs 2.0中使用基本身份验证调用REST服务

我读AgJs 2.0文档中的HTTP类,但我没有找到任何有关基本认证的信息。

任何人都可以提供示例代码来使用基于BASIC认证的Angularjs 2.0中的REST服务吗?

在此先感谢!

最好的问候!

我AgJs 1.3代码:

VAR URL = “http://x.x.x.x:xxxx/data/” +号码;

$http.defaults.headers.common['Authorization'] = 'Basic ' + Base64.encode('username' + ':' + 'password'); 
$http.defaults.headers.common['Content-Type'] = 'application/json'; 

$http({ method: 'GET', url: url }). 
     success(function (data, status, headers, config) { 
      alert(data); 
     }). 
     error(function (data, status, headers, config) { 
      alert("error: " + data); 
     }); 
+0

我不知道你是否与本[问题](https://github.com/angular/angular/issues/3266)中的用户相同,但如果它可以帮助其他人... –

+0

有看看[这个答案](http://stackoverflow.com/a/34465070/995671)到一个类似的问题。 –

回答

0

取决于如果您正在使用新的Angular2 http API,或外在的东西像fetch

如果你可以做这样的事情,只记得有带包后面:

myHeaders = { 
     'Accept': 'application/json', 
     'Content-Type': 'application/json', 
     'Authorization': 'Basic ' + Base64.encode('username' + ':' + 'password') 
    } 
return Zone.bindPromiseFn(fetch)(
      url, 
      { 
       method: 'GET', 
       headers: myHeaders, 
       body: JSON.stringify(myData) 
      }).then(
       r => {return r.json()} 
     ); 
1

我刚刚发表的帖子从angular2到有基本身份验证的服务器和工作的:

sendAuthentification(credentials: string): Observable<any> { 
      var headers = new Headers(); 
      headers.append('Authorization', 'Basic ' + btoa('user:pass')); 

      return this.http.get("http://ip/yourpost", headers}); 
    } 

希望这回答你的问题。

相关问题