Http获取Angular的请求授权

时间:2017-11-20 21:10:07

标签: angular http get http-get

我正在使用API​​为我提供NBA球员的名字和统计数据。 我有以下代码导致我出现401错误(未经授权)。

constructor (private http: Http) {}
fullName;

getPlayerName() {
    this.http.get('https://api.mysportsfeeds.com/v1.1/pull/nba/2016-2017-regular/cumulative_player_stats.json?playerstats=2PA,2PM,3PA,3PM,FTA,FTM').subscribe(data => {
        this.newdata= data.json()
        console.log(this.newdata)
this.fullName = data.json().cumulativeplayerstats.playerstatsentry[0].player.FirstName + " " + data.json().cumulativeplayerstats.playerstatsentry[0].player.LastName
}
}

如何添加用户名和密码进行身份验证?

3 个答案:

答案 0 :(得分:1)

你应该像这个例子那样设置http标题

let headers = new Headers(); headers.append('encrypted_credentials', username + ":" + password);

this.http.get(url,{headers:headers})。subscribe(data => {});

答案 1 :(得分:0)

来自官方文档:https://angular.io/guide/http#headers

One common task is adding an Authorization header to outgoing requests. Here's how you do that:


http
  .post('/api/items/add', body, {
    headers: new HttpHeaders().set('Authorization', 'my-auth-token'),
  })
  .subscribe();

HttpHeaders类是不可变的,因此每个set()都返回一个新实例并应用更改。

答案 2 :(得分:0)

也许这会有所帮助:

this.http.get('https://api.mysportsfeeds.com/v1.1/pull/nba/2016-2017-regular/cumulative_player_stats.json?playerstats=2PA,2PM,3PA,3PM,FTA,FTM', {headers: new HttpHeaders().set('username', myUsername).set('password', myPassword)}).subscribe(// handle Result)