代码之家  ›  专栏  ›  技术社区  ›  koque

为什么req对象中缺少我的用户对象?

  •  0
  • koque  · 技术社区  · 6 年前

    以下函数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) {
    
        })
    }
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Sunil Singh    6 年前

    你已经定义了 getCart 方法有两个参数req和res,但是无论何时调用它,都是在不带任何参数的情况下调用的。这意味着你什么都没通过。

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

    this.cartService.getCart(req,res)
    

    this.cartService.getCart()