为什么我的用户对象从req对象中丢失了?

时间:2018-10-06 20:29:19

标签: angular mongoose

以下函数UserService.signIn()调用服务器以登录用户:

UserService.signIn():

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#signIn()

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 {
            }
        }
    })
}

在返回上面显示的UserService.signIn()之后,在map方法中,它调用CartService.getCart()来检索用户的购物车,如下所示:

 map(token => {
    this.cartService.getCart().subscribe();
 }),

CartService.getCart()然后调用服务器以检索用户的购物车,如下所示:

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#getCart()

exports.getCart = function (req, res) {
    Cart.findOne({
        email: req.user.email
    }).exec(function (err, cart) {

    })
}

1 个答案:

答案 0 :(得分:0)

您已经定义了getCart方法,该方法具有两个参数req和res,但是,无论何时调用它,都没有任何参数。这意味着您什么都没通过。

您必须将调用方法传递为-

this.cartService.getCart(req,res)

代替

this.cartService.getCart()
相关问题