【问题标题】:res is not defined in Node.js (Mongoose)res 没有在 Node.js (Mongoose) 中定义
【发布时间】:2017-06-25 16:34:31
【问题描述】:

如何将 res 放入普通函数中,即不是导出的不属于路由的函数?

function createNewStudent(v,callBackOne){
  if (callBackOne) {
    studentInfo.callBackOneStudent = callBackOne;
  }
  // common filter json
  var filterjson = common.defaultFilterJson();
  filterjson['active'] = true;
  filterjson['email'] = v.email;
  // student initialization
  var student = new Student(v);
  async.waterfall([
    function (done) {
            student.save(function (err) {
              if (!err) {
               studentInfo.callBackOneStudent();
               Employee.update({_id: student.created_by},{"$push": { "students": student._id } }).exec(function (err, employee) { });
               done();
              }
            });
          }
        }
      });
    },
    function (done) {
      var url = config.mailer.studentActivateUrl + student._id;
     ---error is here-----
      res.render('modules/users/server/templates/student-confirmation-email', {
        name: student.first_name + ' ' + student.last_name,
        appName: 'GAIPP',
        url: url
      }, function (err, emailHTML) {
        done(err, emailHTML, student);
      });
    }
});

我的错误是“res”未定义。谁能帮我解决这个错误?

【问题讨论】:

  • res 根本没有在您的整个代码示例中定义。都粘贴了吗?
  • 你把你的节点代码粘贴到这里了吗

标签: node.js mongoose


【解决方案1】:

res 放入函数的唯一方法是在运行时以某种方式将其提供给该函数。请记住,res 仅在请求处理中有意义。在请求处理程序之外,您的函数甚至无法知道要响应哪个请求,因为可能同时处理了多个请求。

如果您想要一个可以访问res 的函数,那么您有以下选择:

在请求处理程序中使用嵌套函数,例如

app.get('/foo', function (req, res) {
  function x() {
    // you can use res here
  }
  x();
});

添加res 作为参数:

function x(res) {
  // you can use res here
}
app.get('/foo', function (req, res) {
  x(res);
});

另一种选择是向您的函数添加一个回调,该回调将由处理程序传递:

function x(args, cb) {
  // you cannot use res here
  // but you can call the callback:
  cb(null, 'something');
}
app.get('/foo', function (req, res) {
  x(function (err, data) {
    if (err) {
      // handle error
    }
    // use res here with data supplied by x()
    res(data);
  });
});

您的x() 函数也可以返回一个promise,而不是使用回调。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-08
    • 2016-12-29
    • 1970-01-01
    • 2011-12-08
    • 1970-01-01
    相关资源
    最近更新 更多