HTTP GET 401 Authorization Required error in angular 6

时间:2018-10-16 16:46:02

标签: api http angular6

我正在尝试连接AWS API。我具有用于基本身份验证的API用户名和密码,并尝试通过GET方法获取一些数据列表。 可以很好地进行发布,但是用角度代码处理时却出现401错误。

401 Authorization Required error

我的代码如下所示,

  public getSavedIntents(): Observable<any> {

    const url = `${this.API_AWS_URL}intent`;  
    const apiUsername = "frontend-dev";
    const apiPassword = "Wo8aedfgsdfg444445454aw5quae5a"; 
    
    var reqHeader = new HttpHeaders();
    reqHeader.append("Content-Type", "application/json");
    reqHeader.append("Access-Control-Allow-Origin", "*");
    reqHeader.append("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    reqHeader.append("Authorization", "Basic " + btoa(apiUsername + ":" + apiPassword));
   
    return this.http
      .post<any>(url, { headers: reqHeader })
      .pipe(
        catchError(err => {
          throw err;
        })
      );
  }

1 个答案:

答案 0 :(得分:0)

我刚刚添加了 reqHeader = reqHeader.append(),而不是 reqHeader.append()

  

reqHeader = reqHeader.append(“ Authorization”,“ Basic” + btoa(apiUsername +“:” + apiPassword));

 public getSavedIntents(): Observable<any> {

    const url = `${this.API_AWS_URL}intent`;  
    const apiUsername = "frontend-dev";
    const apiPassword = "Wo8aedfgsdfg444445454aw5quae5a"; 
    
    var reqHeader = new HttpHeaders();
   reqHeader= reqHeader.append("Content-Type", "application/json");
   reqHeader = reqHeader.append("Access-Control-Allow-Origin", "*");
   reqHeader = reqHeader.append("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    reqHeader = reqHeader.append("Authorization", "Basic " + btoa(apiUsername + ":" + apiPassword));
   
    return this.http
      .post<any>(url, { headers: reqHeader })
      .pipe(
        catchError(err => {
          throw err;
        })
      );
  }