I am getting this error when i try to log out.
`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)`
But when I send the HTTP request from the postman, the code works. I successfully logged out when I used the postman
My Auth Service
`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
}))}
` Here is the code where i Subscribe to this http request:
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")
}
})
}
That error is not from your code (but it's caused by it).
The error references http.js line 165 of Angular HttpClient module, which is the following snippet (in Angular 8 at least):
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);
}
}));
});
Most likely the values of the headers are not being set. I would recommend first removing the headers altogether, and see if the error goes away. If it does go away, add them back one at a time.
See if the token is actually being set (that it's not undefined). You can add a console.log(this.token) at the begining of the logout() method.
Also you don't need to explicitely set the Content-Type most of the time, as Angular can take care of that automatically in most cases. You can remove that, and see if it makes any difference.
The fact that you are being logged out successfully probably means that you are passing the headers properly (explicitely) in Postman, but not passing them propertly in Angular (as indicated by the error). Also, your back-end may just not be doing the validation propertly. So the fact that you can logout with Postman doesn't relate to this issue in a significant way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With