如何从后端提取状态响应代码并在前端中使用它?

时间:2019-02-07 06:23:38

标签: node.js angular express

我试图将状态响应代码从Node.js的后端发送到我的Angular的前端,以便显示错误消息“电子邮件已存在”。

//前端

add.user.component.ts

 if (this.AddUserForm.valid) {
      this.AuthService.register(this.AddUserForm.value)
      .pipe(first())
      .subscribe(
        data => {
            this.router.navigate(['dashboard/user']);
          this.snackbar.open('User has been Added', 'Close', {
            duration: 3000,
          });
        },
        error => {
          this.loading = false;
          this.snackbar.open('Unsuccessful', 'Close', {
            duration: 3000,
          });
        },
      );
    } 

authentication.service.ts

register(user: User) {
    // const headers = new HttpHeaders({ 'Authorization': JSON.parse(localStorage.getItem('currentUser')).token });
    return this.http.post<any>(`${this.environment.userUrl}/auth/register`, user);
  }

//后端

authentication.js

exports.register = function (req, res, next) {

    var email = req.body.email;
    var password = generator.generate({
        length: 10,
        numbers:true,
        uppercase:true,
        symbols: true
    });


    if (!email) {
        return res.status(422).send({
            error: 'You must enter an email address'
        });
    }

    User.findOne({
        email: email
    }, function (err, existingUser) {

        if (err) {

            return next(err);
        }

        if (existingUser) {
            return res.status(422).send({
                error: 'That email address is already in use'
            });
        }

        var user = new User({
            email: email,
             password: password,

        });

        user.save(function (err, user, done) {

            if (err) {
                return next(err);
            }

            var userInfo = setUserInfo(user);

            res.status(201).json({
                message: 'Please Check you Email Address',
                 token: 'JWT ' + generateToken(userInfo),
                user: userInfo
            });

响应代码需要从后端发送到我的前端。在这种情况下,需要将响应状态代码422发送到我的前端

2 个答案:

答案 0 :(得分:0)

您可以在响应对象中添加statuCode值。

if (existingUser) {
            return res.status(422).send({
                error: 'That email address is already in use',
                statusCode: 422
            });
        }

答案 1 :(得分:0)

您应该能够直接在HttpResponse上读取状态,而不必将其包含在响应json中:

this.AuthService.register(this.AddUserForm.value)
  .pipe(first())
  .subscribe(data => console.log(data.status));

您可能还必须将其添加到http调用中:

{observe: 'response'}

它变成这样:

this.http.post<any>(`${this.environment.userUrl}/auth/register`, user, {observe: 'response'});