gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 23:40:02 25 4
gpt4 key购买 nike

我正在尝试向 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com