【问题标题】:node.js & express, redirect or send file after async db searchnode.js & 在异步数据库搜索后快速、重定向或发送文件
【发布时间】:2016-12-01 15:06:36
【问题描述】:

我正在尝试为我的 node.js & express 应用程序编写路由,但遇到了一点问题。

逻辑是这样的:

  1. 用户进入带有特殊标签ID/6758HDE的网站
  2. 如果标签已经存在,我会在数据库中进行异步检查
  3. 如果标签存在,我会滚动新的唯一标签并用它设置网址
  4. 如果标签不存在我允许当前标签并用它设置网址

到目前为止,这是我的代码:

app.get('/*', function(req, res) {
    check_in_db(req.url, function(result) {
        if(result) {
            res.sendFile(__dirname + '/index.html');
        } else {
            res.redirect('/' + roll_new_id());
        }
    });
});

我猜代码不起作用,因为它执行异步数据库搜索,而标题必须立即发送,我记得有类似 next() 的东西来处理这种情况,但我的知识很薄弱,也许有人可以为我指明正确的方向并展示如何更改我的代码,使其按预期工作。

【问题讨论】:

  • 重定向后为什么不尝试下一步?如果它是异步的,它也应该到达那里。

标签: javascript node.js express routing


【解决方案1】:

res.redirect 发生在您的 roll_new_id 函数调用有机会返回新的 id 值之前。要解决这个问题,您必须首先调用roll_new_id,并传入一个回调函数,一旦完成创建新ID,它将调用该函数。一旦创建了新的 id 值,它将执行将新 id 值作为参数传递的回调函数。在传递给roll_new_id 的回调函数中,您将使用在执行回调函数时从roll_new_id 传递的新id 值执行res.redirect。这有意义吗?

function roll_new_id(callbackFunction){

  var new_id;

  // create the new id...

  // pass new_id to the callback function..
  callbackFunction(new_id); 

}

app.get('/*', function(req, res) {

    check_in_db(req.url, function(result) {

        if(result) {

            res.sendFile(__dirname + '/index.html');

        } else {


            roll_new_id(function(theNewId){

              // this is the callbackFunction
              // called from inside the roll_new_id function

              res.redirect('/' + theNewId);

            })

        }
    });
});

你也可以这样写:

function rollNewIDCallbackFunction(theNewId) {

  // this is the callbackFunction
  // called from inside the roll_new_id function

  res.redirect('/' + theNewId);

}

roll_new_id(rollNewIDCallbackFunction);

如果您想使用next 函数,请执行以下操作:

app.get('/*', function(req, res, next) {

    check_in_db(req.url, function(result) {

        if(result) {

            res.sendFile(__dirname + '/index.html');

        } else {

            next(); // call middleware to roll new id

        }
    });

}, function(req, res){ // middleware to roll the new id

  function rollNewIDCallbackFunction(theNewId) {

    // this is the callbackFunction
    // called from inside the roll_new_id function

    res.redirect('/' + theNewId);

  }

  roll_new_id(rollNewIDCallbackFunction);

});

【讨论】:

  • next() 示例的答案正常;)谢谢!
猜你喜欢
  • 2015-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-02
  • 1970-01-01
  • 2014-01-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多