【问题标题】:Getting 401 status code while hitting post url in angular2在angular2中点击帖子网址时获取401状态码
【发布时间】:2017-08-28 07:32:44
【问题描述】:

我正在研究 Angular2。我有一个登录 url,我必须使用它进行发布操作。在 Postman 中,我从 url 获得响应。但是在我尝试的代码中,我得到了 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;

谁能帮我解决这个问题。这里有什么问题?

【问题讨论】:

    标签: angular post authorization


    【解决方案1】:

    很可能您在附加时在标头中发送了错误的信息。请与您的后端确认

    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)
                 });
    

    【讨论】:

    • 无论需要什么信息,我都会发送这些信息。@Pardeep
    • 我不这么认为,因为通常用户名和密码是使用正文部分而不是在标题部分发送的。
    • 是的,通过后端检查,现在编辑了问题,没有发送用户名和密码仍然得到相同的 401 错误。我怀疑我发送请求正文的方式是否正确。@Pardeep跨度>
    • 查看我的更新,如果有正文需要发送JSON.stringify
    • 是的,也试过 JSON.stringify(data) 仍然得到同样的错误。@Pardeep
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-26
    • 2017-11-11
    • 2013-01-20
    • 1970-01-01
    • 2014-10-25
    • 2019-01-16
    • 2013-07-27
    相关资源
    最近更新 更多