TypeError:无法读取nodejs中未定义的属性“发送”

时间:2018-09-03 12:46:32

标签: node.js angular mongodb

我正在使用Angular6,mongodb和nodejs开发注册表。如果用户在数据库中不存在,我在那里写了一个post方法将用户保存在mongodb中。将用户添加到数据库后,应向用户发送电子邮件,并且用户应重定向到另一个视图。该视图也位于较早的html中,并且仅在结果成功时显示。如果数据库中已包含电子邮件名称,则应显示错误消息。我在密码中使用了默认错误消息。针对现有用户的错误消息的strategy-options.ts。但是,当我尝试添加新用户时,它不会导航至下一个视图,并且终端会显示以下错误消息。 TypeError:无法读取未定义的属性“发送” “ .... node_modules \ mongodb \ lib \ utils.js:132”

这是我的保存方法。

router.post('/signup', function(req,  next) {
   console.log("Came into register function.");

    var newUser = new userInfo({
     firstName : req.body.firstName,
     lastName : req.body.lastName,
     rank : req.body.lastName,
     mobile :  req.body.lastName,
     email : req.body.email,
     userName : req.body.userName,
     password : req.body.password,
     status : req.body.status
    });

    newUser.save(function (err, user,res) {
      console.log("Came to the save method");
      if (err){
        console.log(user.email);
        res.send(err);
        return res;
      } 
      else{
        var transporter = nodemailer.createTransport({
          service: 'Gmail',
          auth: {
            user: 't36@gmail.com',
            pass: '12345'
          }
        });

        var mailOptions = {
          from: 'reg@demo.com',
          to: newUser.email,
          subject: 'Send mails',
          text: 'That was easy!'
        };
        console.log("This is the user email"+" "+newUser.email);
        transporter.sendMail(mailOptions, function(error, info){
          if (error) {
            console.log("Error while sending email"+" "+error);
          } else {
            console.log('Email sent: ' + info.response);
          }

        });
        console.log("success");
        return res.send("{success}");

      }

    });

});

这是我在register.component.ts文件中的注册方法。

register(): void {
        this.errors = this.messages = [];
        this.submitted = true;

        this.service.register(this.strategy, this.user).subscribe((result: NbAuthResult) => {
            this.submitted = false;
            if (result.isSuccess()) {
                this.messages = result.getMessages();
                this.isShowConfirm = true;
                this.isShowForm = false;
            }
            else {
                this.errors = result.getErrors();
            }

            const redirect = result.getRedirect();
            if (redirect) {
                setTimeout(() => {
                    return this.router.navigateByUrl(redirect);
                }, this.redirectDelay);
            }
            this.cd.detectChanges();

        });
    }

我在互联网上尝试了很多方法来解决这个问题。但是仍然没有。

2 个答案:

答案 0 :(得分:0)

首先,节点js路由器由3个参数req, res, next组成,您错过了res参数,在这种情况下,next的行为与res参数相同。 其次,Model.save仅返回错误,并且保存的数据中没有res参数。因此,最终代码将如下所示:

router.post('/signup', function(req, res, next) {
 console.log("Came into register function.");
 var newUser = new userInfo({
   firstName : req.body.firstName,
   lastName : req.body.lastName,
   rank : req.body.lastName,
   mobile :  req.body.lastName,
   email : req.body.email,
   userName : req.body.userName,
   password : req.body.password,
   status : req.body.status
 });

newUser.save(function (err, user) {
  console.log("Came to the save method");
  if (err){
    console.log(user.email);
    res.send(err);
    return res;
  } 
  else{
    var transporter = nodemailer.createTransport({
      service: 'Gmail',
      auth: {
        user: 't36@gmail.com',
        pass: '12345'
      }
    });

    var mailOptions = {
      from: 'reg@demo.com',
      to: newUser.email,
      subject: 'Send mails',
      text: 'That was easy!'
    };
    console.log("This is the user email"+" "+newUser.email);
    transporter.sendMail(mailOptions, function(error, info){
      if (error) {
        console.log("Error while sending email"+" "+error);
      } else {
        console.log('Email sent: ' + info.response);
      }

    });
    console.log("success");
    return res.send("{success}");
  }
 });
});

答案 1 :(得分:0)

为了解决同样的错误消息 TypeError: Cannot read property 'send' of undefined 在我的 rest api 应用程序中,我发现我错过了有效的语法 res.status(200).send(data) 或 {{1} }.虽然我在我的控制台中找到了数据。 enter image description here

res.send(data)

当您使用 module.exports.getUsersController = async (req, res) => { try { // Password is not allowed to pass to client section const users = await User.find({}, "-password"); const resData = { users, success: { title: 'All Users', message: 'All the users info are loaded successfully.' } } console.log(resData) // This is not correct // return res.status(200).res.send(resData); // It should be return res.status(200).send(resData); } catch (err) { console.log(err) return res.status(500).send(err); } }; 时,您必须在此之后使用 res.status(),不要再次使用 .send()

我认为这对也犯过同样错误的开发人员会有所帮助。快乐的开发者!