如何使用角度HttpClient进行基本授权并连接api请求?

时间:2018-04-26 22:13:12

标签: api request http-headers httpclient angular5

好吧,我有一个问题,我试图连接api与基本授权,但服务器不给我访问它返回401(unautorized)我的代码是:

getApi() {
        console.log('here i am in the method for get extensions');
        const headers = new HttpHeaders({
            'Content-Type': 'application/json',
            'Authorization': 'Basic ***********************'
        });
        const options = {
            headers,
            withCredentials: true
        };
        // tslint:disable-next-line:max-line-length
        return this.http.post('https://10.100.43.241/json', this.jsonBody, options).map((response: Response) => {
            const resToJSON = JSON.stringify(response);
            console.log('i am going to return jsonfrom method');
            return resToJSON;
        });
    }

我也试过postman an it is working as well。我真的需要知道如何解决这个连接或授权问题

注意:我不是服务器的管理员

1 个答案:

答案 0 :(得分:0)

尝试这种架构。

组件:

this._appApiService.getApi(this.jsonBody).subscribe(result => {
   this.resToJSON = result; 
});

服务:

getApi(jsonBody: any) {
    // add authorization header with jwt token
    let headers = new HttpHeaders({ 'Authorization': 'Bearer ' + this.token });
    let options = { headers: headers };

    return this.http.post(this.baseUrl + 'https://10.100.43.241/json', this.jsonBody , options);
  }