简体   繁体   中英

HTTP request status undefined in angular

I want to get the response (status code) of an http request from my node server and if it returns 200, i want to redirect the user. For some reason, res.status is undefined, and I have no idea why

Heres the code for the component:

  submit(){
    this.auth.tryLogin(this.form.getRawValue())
    .subscribe(res => {
      console.log(res);
      if(res.status == 200){
        this.router.navigate(['/'])
      }
      else{
        alert(res.status)
      }
    })
  }

The service:

 tryLogin(data : any){
    return this.http.post(environment.server + environment.routes.authRoutes.login, data, this.options)
  }

And the router for the request:

router.post('/login', async (req, res) => {     //login     TODO: possibly rebuild this function to only return "wrong username or password"
    try{
        let user = await User.findOne({email: req.body.email.toLowerCase()}); //looks for the email address in the db

        if(!user){      //if the user doesnt exist
            return res.status(400).send({
                message: 'user does not exist'
            });
        }
        
        if(!user.isVerified){     //if the user didnt verify his email address
            return res.status(401).send({
                message: 'user is not verified'
            })
        }

        if(!await bcrypt.compare(req.body.password, user.password)){    //if the passwords dont match
            return res.status(400).send({
                message: 'wrong password'
            });
        }
    
        let token = jwt.sign({_id: user._id}, secret);  //jwt token for auth
    
        res.cookie('jwt', token, {  //token gets stored as a cookie
            httpOnly: true,
            maxAge: 24 * 60 * 60 * 1000 //exp time 24 hours'
        });
    
        return res.status(200).send({
            message: 'successfully logged in'
        });
    } catch (e) {
        console.log(e.name + ": " + e.message);
        return res.status(500).send({
            message: 'An error occoured!'
        })
    }
});

I think you need to set observe property in your http options, the default is body, what you need here is observe response, read the docs here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM