节点express:模拟app.get中的授权函数

node express: mock authorize function in app.get

本文关键字:授权 权函数 get app express 模拟 节点      更新时间:2023-09-26

我在node/express中练习简单的。get方法。我正在遵循一本书的示例,但我没有会话变量,也没有模板;所以我注释了这几行,并将它们替换为一个简单的。send方法,并替换为一个简单的硬编码变量:authorized.

我得到错误:ReferenceError: res is not defined

问题是我没有res变量,因为控制首先通过授权函数。

function authorize(req, res, next){
    authorized = true;
    // if(req.session.authorized) return next();
    if(authorized) return next();
    res.send('not-authorized');
}
app.get('/secret', authorize, function(){
    // res.render('secret');
    res.send('secret');
});
app.get('/sub-rosa', authorize, function(){
    // res.render('sub-rosa');
    res.send('sub-rosa');
});

多亏了注释,解决方案是:

function authorize(req, res, next){
    authorized = true;
    // if(req.session.authorized) return next();
    if(authorized) return next();
    res.send('not-authorized');
}
app.get('/secret', authorize, function( req, res ){
    // res.render('secret');
    res.send('secret');
});
app.get('/sub-rosa', authorize, function( req, res ){
    // res.render('sub-rosa');
    res.send('sub-rosa');
});