【问题标题】:TypeError: Cannot read property 'send' of undefined in nodejsTypeError:无法读取nodejs中未定义的属性“发送”
【发布时间】:2021-06-24 15:56:22
【问题描述】:

我正在使用 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();

        });
    }

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

【问题讨论】:

    标签: node.js angular mongodb


    【解决方案1】:

    首先,节点 js 路由器由 3 个参数 req, res, next 组成,您错过了 res 参数,在您的情况下,next 表现为 res 参数。 其次 Model.save 只返回错误和保存的数据,其中没有 res 参数。所以finally的代码会是这样的

    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}");
      }
     });
    });
    

    【讨论】:

      【解决方案2】:

      为了解决同样的错误消息 TypeError: Cannot read property 'send' of undefined 在我的 rest api 应用程序中,我发现我错过了有效的语法 res.status(200).send(data)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(),而不是再次使用res

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-09
        • 2017-03-06
        • 2020-06-17
        • 2021-11-02
        • 2020-08-10
        • 2022-09-23
        • 2022-11-29
        • 2017-08-30
        相关资源
        最近更新 更多