类型错误:无法读取未定义属性的长度(Angular 8)(标题)

4

当我尝试注销时,出现了这个错误。

`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)`

但是当我使用Postman发送HTTP请求时,代码起作用。我在使用Postman时成功退出了登录

我的身份验证服务

`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")
      }
    })
  }

1
你不确定问题出在哪里,你是在哪里调用length的? - JSmith
你尝试过这些建议了吗?你解决了你的问题吗? - ulmas
2个回答

5

这个错误不是由你的代码造成的(但是它是由它引起的)。

这个错误引用了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);
                }
            }));
        });

很可能头部的值没有被设置。建议先全部删除头部,看看错误是否消失。如果错误消失了,逐个添加回来。

检查token是否实际设置(不是未定义的)。您可以在logout()方法的开始处添加console.log(this.token)。

大多数情况下,您不需要显式设置Content-Type,因为Angular可以自动处理大多数情况。您可以删除它,看看是否有任何差异。

您能够成功退出登录可能意味着您已经正确传递了头部(显式)到Postman,但在Angular中没有正确传递它们(正如错误所示)。此外,您的后端可能只是没有正确进行验证。因此,您可以使用Postman注销,但这与此问题没有明显的关系。


0

我认为头文件没有被设置。您可以尝试以这种方式设置头文件 在您的类中创建一个属性headers: any = ''

this.headers = new HttpHeaders().set("Content-Type", "application/json") .set("Authorization",this.token)

然后在请求中使用它们


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接