ax1*_*x1o 4 authentication angular angular-httpclient
当我尝试注销时出现此错误。
`core.js:6014 ERROR TypeError: Cannot read property 'length' of undefined
    at http.js:165
    at Array.forEach (<anonymous>)
    at HttpHeaders.lazyInit (http.js:153)
    at HttpHeaders.init (http.js:274)
    at HttpHeaders.forEach (http.js:376)
    at Observable._subscribe (http.js:2342)
    at Observable._trySubscribe (Observable.js:42)
    at Observable.subscribe (Observable.js:28)
    at subscribeTo.js:20
    at subscribeToResult (subscribeToResult.js:7)`
但是当我从邮递员发送 HTTP 请求时,代码就可以工作了。我在使用邮递员时成功退出
我的认证服务
`logout(user){
    let headers = new HttpHeaders({
      'Content-Type': 'application/json',
      'Authorization': this.token }); //this.token is the value of token(eyJhbGciOiJIUzI1NiIsInR5cCI6IkpX...)
  let options = { headers: headers };
    localStorage.clear()
    this.token=null;
    return this.http.post<response>('http://localhost:3000/users/logout',null,options).pipe(map(res=>{
      console.log(res)
       return res
    }))}
` 这是我订阅此 http 请求的代码:
 onLogout(){
    this.authService.logout(this.dataService.storingToken).subscribe(res=>{
      console.log(res)
      if(res.status===true){
      this.router.navigate(["/login"])
 }else{
        console.log("some error has occurred")
      }
    })
  }
该错误不是来自您的代码(但它是由它引起的)。
该错误引用了 Angular HttpClient 模块的 http.js 第 165 行,它是以下代码片段(至少在 Angular 8 中):
        this.lazyInit = (/**
         * @return {?}
         */
        () => {
            this.headers = new Map();
            Object.keys(headers).forEach((/**
             * @param {?} name
             * @return {?}
             */
            name => {
                /** @type {?} */
                let values = headers[name];
                /** @type {?} */
                const key = name.toLowerCase();
                if (typeof values === 'string') {
                    values = [values];
                }
                if (values.length > 0) { // <=== THIS IS WHERE THE ERROR IS ===
                    this.headers.set(key, values);
                    this.maybeSetNormalizedName(name, key);
                }
            }));
        });
很可能没有设置标头的值。我建议首先完全删除标题,然后看看错误是否消失。如果它确实消失了,请一次添加一个。
查看令牌是否确实被设置(它不是未定义的)。您可以在 logout() 方法的开头添加 console.log(this.token) 。
而且大多数时候你不需要显式地设置 Content-Type,因为 Angular 在大多数情况下可以自动处理这个问题。您可以将其删除,看看是否有任何区别。
您成功注销的事实可能意味着您在 Postman 中正确(显式)传递标头,但没有在 Angular 中正确传递它们(如错误所示)。此外,您的后端可能没有正确进行验证。因此,您可以使用 Postman 注销这一事实与此问题没有重大关系。
| 归档时间: | 
 | 
| 查看次数: | 3988 次 | 
| 最近记录: |