node.js - 将参数传递给expressjs中的中间件函数

标签 node.js express

我正在尝试向 nodejs 添加缓存功能。

我想要这样的代码,

app.get('/basement/:id', cache, (req,res) =>  {
   client.set('basement' + req.params.id,'hello:'+req.params.id)
   res.send('success from source');
});


function cache(req,res,next) {
    console.log('Inside mycache:' + req.params.id);
    client.get('basement' + req.params.id, function (error, result) {
        if (error) {
            console.log(error);
            throw error;
        } else {
            if(result !== null && result !== '') {
                console.log('IN  Cache, fetching from cache and returning it');
                console.log('Result:' + result);
                res.send('success from cache');

            } else {
                console.log('Not in Cache, so trying to fetch from source ');;
                next();
            }
        }
    });
}

我想将名为 cache 的中间件函数应用于 /basement/:id 路由收到的请求。

缓存函数将接收 key 作为其参数。 在缓存中,我想检查缓存是否存在,如果存在则从那里返回它,否则我想调用实际的路由处理程序。 key 基于一个或多个请求参数。

这样,我最终将为我的应用程序中的每个处理程序编写一个单独的缓存函数。

我的缓存函数中的逻辑是对键的通用期望,它基于实际的请求对象,并且可能因方法而异。

所以,我想要一个可以将键作为参数的通用缓存函数,这样我就可以拥有这样的代码,

app.get('/basement/:id', cache, (req,res) =>  {
    client.set('basement' + req.params.id,'hello:'+req.params.id)
    res.send('sucess from source');
});

我的意思是我会将缓存键传递给缓存函数。因此,缓存功能可以是通用的。

但是,如果我像下面这样更改我的缓存函数以接收缓存键,它就不起作用。

function cache(cachekey,req,res,next) {

}

似乎我的缓存函数中不能有另一个参数来接收传递的参数。

我想将缓存键作为参数传递给函数。

如果有人遇到过类似的问题,你能帮我解决这个问题吗?

最佳答案

But, if I change my cache function like below as so as to receive the cache key, it does not work.

你不能因为它不是一个有效的 express 中间件(它实际上是一个错误中间件),express 将通过:req, res, next 按此顺序。和 err, req, res, next 用于错误中间件。

您的缓存函数将需要返回一个中间件,因此您可以将 key 传递给它。

I wanted to create a generic cache function which can take any cache key. In this case it was id, but other cases may have different keys

function cache(key, prefix = '') {

    // Or arrange the parameters as you wish to suits your needs
    // The important thing here is to return an express middleware
    const cacheKey = prefix + req.params[key];
    return (req, res, next) => {

        console.log('Inside mycache:' + cacheKey);
        client.get(cacheKey , function(error, result) {
            if (error) {
                console.log(error);
                return next(error); // Must be an error object
            }

            if (result !== null && result !== '') {
                console.log('IN  Cache, fetching from cache and returning it');
                console.log('Result:' + result);
                return res.send('success from cache');

            }

            console.log('Not in Cache, so trying to fetch from source ');;
            next();

        });

    }
}

现在你可以像这样使用它了:

app.get('/basement/:id', cache('id', 'basement'), (req, res) => { /* ... */ });
app.get('/other/:foo', cache('foo', 'other'), (req, res) => { /* ... */ });

关于node.js - 将参数传递给expressjs中的中间件函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50989393/

相关文章:

javascript - 当新的 couchbase Node 添加到集群时,是否需要更改应用程序?

c++ - 可以构建自定义 node.js 插件但不能包含

javascript - 尝试使用 socket.io 时出错

node.js - 从多个集合 MongoDB 创建 View

javascript - Discord API 对于使用机器人 token 的所有查询返回 401

javascript - 复选框和 Node JS

node.js - TeamCity、NodeJS 和 API 测试

Node.js json 文件被另一个调用覆盖

Javascript 超出最大调用堆栈大小错误

javascript - 在 Express 中获取无法 POST/错误