繁体   English   中英

ExpressJS变量未定义

[英]ExpressJS variable undefined

我有一个ExpressJS应用,当用户向路由发出POST请求时,它应该使用req.params.formId在MongoDB中查找ID。

我有一些console.log语句用于调试,因此我可以看到返回的信息。

路由应查找传递的ID,并在找到ID时使用req.body数据以及MongoDB文档中的字段,但这似乎返回undefined

这是路线的代码:

app.post("/api/v1/forms/:formId", (req, res) => {
    const { name, email, message } = req.body;
    console.log(req.body);

    Form.findById(req.params.formId, Form.recipient, err => {
      if (err) {
        res.send(err);
      } else {
        const formRecipient = Form.recipient;

        const newForm = {
          name,
          email,
          message,
          recipient: formRecipient
        };
        console.log(newForm);
        const mailer = new Mailer(newForm, contactFormTemplate(newForm));
        try {
          mailer.send();
          res.send(req.body);
        } catch (err) {
          res.send(err);
        }
      }
    });
  });

所以一个例子,如果我做一个POST请求到localhost:5000/api/v1/forms/5ad90544883a6e34ec738c19的执行console.log newForm节目{ name: ' Mr Tester', email: 'person@example.com', message: 'Hi there', recipient: undefined }

猫鼬模式表单有一个名为recipient的字段

正确的方法是提供要获取的字段作为第二个参数:

Form.findById(req.params.formId, 'recipient', (err, form) => {

   if (err) {
     // error handling code
   } else {
     const formRecipient = form.recipient;
   }
   ...
});

这是Docs

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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