网站搜索

api - Angular 2 | 401 未经授权


你好,我正在构建一个只使用令牌获取 API 数据的简单应用,但我遇到了未授权访问错误...

有人能帮我弄明白为什么我会遇到这个错误吗?

401 未授权

import { Component, ViewEncapsulation } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css'],
      encapsulation: ViewEncapsulation.None,
    })
    export class AppComponent {

    data: any = {};

        constructor( private http: Http ) { }

        ngOnInit() {
            this.getVoicepicData();
            this.getData();
        }

        getData(){
            let headers = new Headers({
                'Token': "TOKEN HERE",
                'Content-Type': 'application/json'
            });

            return this.http.get('http://apiURL.com/api/voice/get-voice-pick-
            file/', { headers: headers })
                .map((res: Response) => return res.json())
        }

        getVoicepicData() {
            this.getData().subscribe(data => {
                console.log(data)
                this.data = data
            })
        }

    }

我该如何处理这个错误?有人能帮我弄明白吗?我设置的令牌正确吗?

编辑: 缺少 import { Headers } from '@angular/http';

答案#1

试试这个:

let headers = new Headers({
                'Authentication': "bearer <space><TOKEN HERE>",
                'Content-Type': 'application/json'
});