【问题标题】:Angular httpHeaders post menthod can't set parametersAngular httpHeaders post menthod 无法设置参数
【发布时间】:2020-02-10 07:32:56
【问题描述】:

我正在尝试使用以下方法从 RestAPI 获取 authtoken。 相同的 url、Params 和 Headers 从邮递员返回给我正确的响应。 但在角度我得到401未经授权的错误。 请帮助我了解我做错了什么? 我无法理解为什么我的标头在 httpHeaders 内的 lazyUpdate 对象内。

提前致谢。

login(loginData) {
const httpOptions = {
  headers:new HttpHeaders().set("Authorization", "Basic " + btoa("username:password")).set("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8").set("access-control-allow-credentials",'true'),
  params:new HttpParams().set('username', loginData.email).set('password', loginData.password).set('grant_type', 'grant_type')
}
this.http.post('http://xx.xx.xx.xx:xxxxx/oauth/token', httpOptions).subscribe(
  data => {
    this.saveToken(data);
    return true;
  },
  err => {
    alert('Invalid Credentials')
    return false;
  });

}

请找到从浏览器发送的标头的附加屏幕截图。

【问题讨论】:

    标签: angular http-headers httpclient angular-httpclient


    【解决方案1】:

    使用 HTTP 标头选项作为发布请求中的第三个参数。

    login(loginData) { 
    
        let httpOptions = {
            headers: new HttpHeaders({ 
                "Access-Control-Allow-Credentials": "true",
                "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
                'Authorization' :  "Basic " + btoa("username:password"),
                'username': loginData.email,
                'password': loginData.password,
                'grant_type': 'grant_type' 
            }) 
        };
    
        this.http.post('http://xx.xx.xx.xx:xxxxx/oauth/token', {},  httpOptions).subscribe( data => {
            this.saveToken(data);
            return true;
        },
        err => {
            alert('Invalid Credentials')
            return false;
        });
    
    }
    

    【讨论】:

      【解决方案2】:

      post 方法的第二个参数是 HTTP 调用的body 负载。您需要使用第三个参数,该参数用于选项。您可以为 body 参数传递一个 null 值,但没有 body 的 post 调用通常是滥用的迹象。

      this.http.post('http://xx.xx.xx.xx:xxxxx/oauth/token', null, httpOptions)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-05-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-27
        相关资源
        最近更新 更多