以下函数UserService.sign in()调用服务器以登录用户:
public signIn(credentials) {
let body = JSON.stringify(credentials);
return this.httpClient.post(this.userUrl, body, httpOptions)
.pipe(
map(token => {
this.cartService.getCart().subscribe();
}),
catchError(this.handleError.bind(this))
)
}
服务器的signIn函数将用户对象存储在req对象上,如图所示:req.user=user。req.user被记录到控制台并显示期望值。
user.server.controller登录()
exports.signin = function(req, res) {
const email = req.body.email;
const password = req.body.password;
User.findOne({
email:email
}).exec(function(err, user) {
if(err) {
} else if(user == null) {
}else {
if(bcrypt.compareSync(password, user.password)) {
console.log('user found', user)
var token = jwt.sign({name:user.name, email:user.email},
config.sessionSecret, {expiresIn:3600});
req.user = user;
console.log('\nuser.server.controller#req.user', req.user)
res.status(200).json(token);
return;
} else {
}
}
})
}
map(token => {
this.cartService.getCart().subscribe();
}),
然后调用服务器检索用户的购物车,如图所示:
public getCart() {
return this.httpClient.get(this.cartUrl)
.pipe(
tap(cart => this.logger.log('cart', cart))
)
}
在cart.server.controller#getCart()中,我尝试使用先前在调用user.server.controller#signIn()期间保存到req对象的req.user电子邮件,但我得到一个错误,req.user未定义。
cart.server.controller获取购物车()
exports.getCart = function (req, res) {
Cart.findOne({
email: req.user.email
}).exec(function (err, cart) {
})
}