如何使用 Angular HttpClient 进行基本授权并连接 API 请求?

问题描述 投票:0回答:1

我尝试连接具有基本授权的 API,但服务器不给我访问权限,它返回 401(未经授权)。我的代码是:

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

我真的需要知道如何解决这个连接或授权问题。

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

http-headers httprequest angular5 angular-httpclient
1个回答
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);
  }
© www.soinside.com 2019 - 2024. All rights reserved.