我一直对我的第一个MEAN堆栈应用。 目前,我能注册新用户并重新登录他们。但是,当我这样做是(登录或注册),我无法刷新主页没有得到登出。
我已经成功地设置我的本地存储,并可以在我父组件得到它,但问题依然存在。 我一直在寻找通过大量的做题,但似乎无法钉下来。
这里是我的登陆后路径
//LOGIN POST
router.post('/login', (req, res) => {
let email;
let password;
if(req.body.email && req.body.password) {
email = req.body.email;
password = req.body.password;
}
if (email === "" || password === "") {
res.status(401).json({message: "Please provide both email and password"});
return;
}
//Find the user in database.
User.findOne({ "email": email }, (err, user) => {
if ( !user ){
res.status(401).json({message: "Email doesn't exist!"});
} else {
bcrypt.compare(password, user.password, function(err, isMatch) {
if (!isMatch) {
return res.status(401).json({message: "Password doesn't match. Please try again..."});
} else {
req.session.user = user; //Storing user data in the session
var payload = {id: user._id};
var token = jwt.sign(payload, jwtOptions.secretOrKey, { expiresIn: "24h" });
return res.json({ message: "ok", token: token, user: user });
// res.status(200).json({message: "Welcome back...", token: token, user: user});
}
});
}
});
});
这里是我的登录方法在我authService
public token: string;
isAuth: EventEmitter<any> = new EventEmitter();
login(user) {
return this.http.post(`${this.BASE_URL}/login`, user)
.map((response) => {
console.log("here's the response", response);
console.log("here's the token", response.json());
let token = response.json() && response.json().token;
// let currentUser = response.json().user;
let currentUser = JSON.stringify(response.json().user);
if(token) {
console.log("here's the token", token);
//set token property
this.token = token;
this.isAuth.emit(true);
//store username and jwt in local storage to keep user logged in between page refreshes
localStorage.setItem('token', token);
localStorage.setItem('user', currentUser);
return true; //return true to indicate successful login
} else {
return false;
}
})
.catch((err) => {
return Observable.throw(err);
});
}
下面是我在分类组件(父组件)正在做
isAuth: boolean;
user: any;
token: any;
constructor(
private session: AuthService,
private router: Router
) {
//checks isAuth event emitter in login to see if it's true. If it is, subscribe the result to our local isAuth variable
this.session.isAuth
.subscribe((isAuth: boolean) => this.isAuth = isAuth );
//if token exists, authenticated
if (this.session.token) {
this.isAuth = true;
localStorage.getItem('token');
localStorage.getItem('user');
//if not, not authenticated
} else {
this.isAuth = false;
}
}
ngOnInit() {
localStorage.getItem('token');
localStorage.getItem('user');
}
我要指出的是,当我让他们以后CONSOLE.LOG我localStorage的项目,他们出现就好了。 我已经试过各种组件上面的代码,但不断收到注销。
任何帮助深表感谢。 有谁知道可能会发生在这里? 非常感谢。