簡體   English   中英

TypeError:無法讀取未定義的屬性“長度”(Angular 8)(標題)

[英]TypeError: Cannot read property 'length' of undefined (Angular 8)(header)

當我嘗試注銷時出現此錯誤。

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

該錯誤不是來自您的代碼(但它是由它引起的)。

該錯誤引用 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);
                }
            }));
        });

很可能沒有設置標題的值。 我建議首先完全刪除標題,然后查看錯誤是否消失。 如果 go 消失了,一次添加一個。

查看令牌是否實際被設置(它不是未定義的)。 您可以在 logout() 方法的開頭添加一個 console.log(this.token)。

此外,大多數情況下您不需要顯式設置 Content-Type,因為 Angular 在大多數情況下可以自動處理。 您可以刪除它,看看它是否有任何區別。

您成功注銷的事實可能意味着您在 Postman 中正確(明確地)傳遞了標題,但沒有在 Angular 中正確傳遞它們(如錯誤所示)。 此外,您的后端可能只是沒有正確地進行驗證。 因此,您可以使用 Postman 注銷這一事實與此問題沒有重大關系。

我認為沒有設置標題。 您可以嘗試以這種方式設置標題 Create a property headers: any = '' in your class

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

然后在您的請求中使用它們

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM