当我尝试注销时出现此错误。
`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 请求时,代码有效。 I successfully logged out when I used the 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);
}
}));
});
很可能没有设置 header 的值。我建议首先完全删除 header ,然后查看错误是否消失。如果它确实消失了,请一次将它们添加回来。
查看 token 是否实际被设置(它不是未定义的)。您可以在 logout() 方法的开头添加一个 console.log(this.token)。
此外,大多数情况下您不需要显式设置 Content-Type,因为在大多数情况下 Angular 可以自动处理。您可以删除它,看看它是否有任何不同。
您成功注销的事实可能意味着您在 Postman 中正确(显式)传递了 header ,但没有在 Angular 中正确传递它们(如错误所示)。此外,您的后端可能只是没有正确地进行验证。因此,您可以使用 Postman 注销这一事实与此问题没有重大关系。
关于angular - 类型错误 : Cannot read property 'length' of undefined (Angular 8)(header),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58513178/