我现在正困扰着一个奇怪的情况。我正在尝试创建一个简单的身份验证应用程序。直到现在都很好。
在我的应用程序中,我将登录验证发送到使用 Express 创建的后端。然后它确认并向前端发送 ok 响应。这是问题所在。当我登录后尝试单击主页时,它会正确显示主页:
但是当我尝试将浏览器定位到“http://localhost:4200/”时,它不会显示已经将我的 homecomponent 路径设置为“”的 home 组件:
它应该显示它,因为 . 所以这里是代码:
应用路由模块
const routes: Routes = [
{
path: '',
component: HomeComponent,
canActivate: [AuthGuard]
},
{
path: 'login',
component: LoginComponent
},
{
path: 'register',
component: RegisterComponent
}
];
认证卫士
canActivate(): boolean {
if(this._cookieService.get('access_token')) {
return this._authService.loggedIn();
} else {
this._router.navigate(['login']);
return false;
}
}
这是身份验证服务
_registerURI = 'http://localhost:3000/auth/register';
_loginURI = 'http://localhost:3000/auth/login';
_token = 'http://localhost:3000/auth/VpW02cG0W2vGeGXs8DdLIq3dQ62qMd0';
isIt: boolean = false;
token = {};
user = {
name: ''
};
constructor(
private http: HttpClient,
private _cookieService: CookieService) { }
registerUser(user) {
return this.http.post<any>(this._registerURI, user, {withCredentials: true});
};
loginUser(user) {
return this.http.post<any>(this._loginURI, user, {withCredentials: true});
};
getToken() { // this is for the validation of token
return this.http.post<any>(this._token, this.token, {responseType: 'json', withCredentials: true});
}
loggedIn(): boolean {
this.getToken().subscribe(res => {
if(res.success === true){
this.isIt = true;
}
}, err => {
if(err.status === 401){
this.isIt = false;
alert('You need to sign in.');
}
console.log(err);
})
return this.isIt;
}
提前致谢!