【问题标题】:nodejs express redirecting from within a event handlernodejs从事件处理程序中快速重定向
【发布时间】:2016-07-26 18:11:34
【问题描述】:

我正在开发的 nodejs 应用程序是使用 express 和 路由中间件。我正在添加某种许可功能 此应用程序会定期检查是否过期。

发现过期后,发出授权失败事件 在事件处理程序中捕获。我想重定向或打开一个新页面 在事件处理程序中。

  1. 这是正确的方法吗? (我是 node 和 js 的新手)
  2. 我无权访问事件处理程序中的响应对象。 那么在这种情况下我如何重定向到不同的页面?

    //Start of the code
    var app = express();
    
    //view engine setup
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'jade');
    //Deleted the code to keep it minimal
    
    app.use('/', routes);
    app.use('/sensor', sensorPage);
    app.use('/export', exportPage);
    app.use('/exportsensormetrics', exportSensorMetricsPage);
    
    //Error Handling
    app.use(function(req, res, next)
    {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
    });
    
    
    //The product key authorise() function periodically checks for expiry
    
    
    var authutils = require('./authutils.js');
    authutils.authorise();
    
    //This is the Event Handler
    
    authutils.authEvent.on('authorisation', function(data)
    {
        if(data == 'passed')
    {
        utils.dump("authutils::authEvent::on: Authorisation Passed");
    }
    else if(data == 'failed')
    {
        //Auth failed
        //I want to redirect from here and open page which says expired
        //Can I redirect from here?
    }
    });
    

【问题讨论】:

    标签: javascript node.js redirect express


    【解决方案1】:

    学习如何使用 Express 的最佳方式 - 官方阅读 docs


    检查许可中间件

    function checkLicense(req, res, next) {
        if (*check*)
            next(); // move to sensorPage 
        else
            next(new Error('License exiped')); // move to first registered error-middlware
    }    
    

    将此中间件分配给应用程序

    app.use(checkLicense); // if you want check all request
    ...
    app.use('/sensor', checkLicense, sensorPage); // if you need check only specific route
    

    error中间件必须有第一个参数error

    app.use(function(err, req, res, next) {...});
    

    【讨论】:

    • 感谢 Aikon 的回复。有没有办法可以避免将其与请求捆绑在一起?我想在后台运行此检查,并且每当它达到条件时,我想打开一个页面?
    • 这有点奇怪,但你可以做到。简单的方法是:客户端每 N 秒向服务器发送 ajax-request 并解析服务器答案。如果未检查许可证,则客户端执行location.href = '/badLicense'。另一种方法是使用 websocket:服务器通过计时器验证所有客户端的许可证,并通过 websocket 发送许可证无效的消息。客户收到后前往badLicense页面。
    • 谢谢艾康。我使用了第二种方法,即使用 Webscokets 与客户端进行通信,并且它正在工作。非常感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-14
    • 1970-01-01
    • 1970-01-01
    • 2019-05-11
    • 1970-01-01
    • 2021-03-25
    相关资源
    最近更新 更多