在angular2中点击post url时获取401状态代码

时间:2017-08-28 07:32:44

标签: angular post authorization

我正在研究Angular2.I有一个登录网址,我必须做后期操作。在Postman我收到来自网址的回复。但在我尝试的代码中,我收到 401状态代码,错误是授权标题中的用户凭据无效。 但我在标题中提供了正确的用户凭据。

 public getData(data: string) : Promise<any> {


     if(typeof(this.login_data) === "undefined") {
       let headers = new Headers();
       headers.append("Authorization", "Basic " + btoa(this.username + ":" + this.password));
        headers.append("Content-Type", "application/json");
        headers.append("Accept", "application/json");

        headers.append("id", this.custid);

         let rOptions = new RequestOptions({

               headers: headers,
               body : data
             });
         return this.http.post(this.loginUrl, rOptions)
             .toPromise()
             .then(res => {
                           this.login_data = res.json().response;
                           return this.login_data;
             })
             .catch(this.handleError);

      } else {
          return Promise.resolve(this.login_data);
      }
}

getData方法在我的服务类中。使用下面的代码调用该方法。

 this.service.getData(JSON.stringify(requestBody))
         .then((response: Response) => {

             if (response.status === 200){
              //if success do next
             } 

         }).catch( error => {

           this.error_message = error.error;

           console.log("error in component and error is: " + JSON.stringify(error));
         } );

在请求者中我传递了这个。

 let requestBody = {};
       let request = {};

       request['username'] = this.user.username;
       request['password'] = this.user.password;
       request['id'] = this.custid;


       requestBody['request'] = request;

任何人都可以帮我解决这个问题。这里有什么问题?

1 个答案:

答案 0 :(得分:0)

很可能你在附加时在标题中发送了错误的信息。请与您的后端联系

headers.append("Authorization", "Basic " + btoa(this.username + ":" + this.password));
        headers.append("Content-Type", "application/json");
        headers.append("Accept", "application/json");
        headers.append("username", this.username);
        headers.append("password", this.password);
        headers.append("id", this.custid);

         let rOptions = new RequestOptions({

               headers: headers,
               body : JSON.stringify(data)
             });