【问题标题】:How do I use another function/multiple functions inside of an Express route in order to manipulate data from a database?如何在 Express 路由中使用另一个函数/多个函数来操作数据库中的数据?
【发布时间】:2017-09-12 19:07:53
【问题描述】:

我正在使用 Express 和 MySQL,我希望能够从 connection.query 检索数据,然后在同一路由中的其他函数中使用该数据。我希望能够在 app.post 的另一个函数中使用在 connection.query 中创建的数组,但是我不知道这样做的最佳方法是什么。我曾尝试使用 Express 所需的单独文件中编写的实用程序函数,但我无法将 MySQL 连接中的数据获取到写入外部文件中的函数中,我什至不确定这是否是正确的方法做我想做的事。

这是我的代码,我想做的可能是能够将forEach 方法放在它自己的函数中,然后在查询之后在另一个函数中使用返回的数组来处理它等等开。

app.post('/submit', function(req, res) {
  var getPosition = "SELECT ID, position FROM routes";
  var posArray = [];
  connection.query(getPosition, function(err, results) {
    if (err) throw err;
    results.forEach(function(item) {
      posArray.push(item.position);
      return posArray;
    }); //end if
  });
}); // end app.post

【问题讨论】:

  • 你的return 毫无意义。
  • 你需要使用回调或承诺。

标签: javascript mysql node.js express


【解决方案1】:

您可以链接中间件来实现此目的:

app.post('/submit', getDataFromDatabase, processData); // end app.post

function getDataFromDatabase(req, res, next) {
  var getPosition = "SELECT ID, position FROM routes";
  var posArray = [];
  connection.query(getPosition, function(err, results) {
    if (err) throw err;
    results.forEach(function(item) {
      posArray.push(item.position);
      req.posArray = posArray;  //attach the data that you want to use later to your req object
    }); //end if

    next(); //Call the next middleware;
  });
}

function processData(req, res, next){
    //Do whatever you want with req.posArray;

    res.json(posArray);  //respond to the client with the posArray (or whatever the client asked for)
}

【讨论】:

  • 谢谢!是否可以将这些中间件包含在服务器内部但在您演示的 app.get/app.post 方法之外?
  • 是的。它们的行为与内联函数相同,但更易于阅读。
猜你喜欢
  • 2017-07-28
  • 2017-03-31
  • 1970-01-01
  • 1970-01-01
  • 2021-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-08
相关资源
最近更新 更多