我有这段代码获取路径“/img”中的最后 10 个 url 请求并将其放入一个数组中,然后我有两个条件。如果数组长度已经是 10,则删除最后一个索引并将新索引添加到列表的开头。和其他如果 url 的索引已经在数组中删除那个,所以我在这个列表中没有任何重复的 url。这是代码:
let recentPaths = [];
app.use('/img', (req, res, next) => {
const index = recentPaths.indexOf(req.originalUrl);
if (recentPaths.length === 10) {
recentPaths.pop();
}
if (index !== -1) {
recentPaths.splice(index, 1);
}
recentPaths.unshift(req.originalUrl);
next();
});
然后我有这个 get 函数,这是我想要从该数组中获取数据的地方。这是代码:
app.get('/stats/paths/recent' ,sendRecentPaths);
async function sendRecentPaths(req, res) {
res.json(recentPaths);
}
它正在工作,但我的问题是,我可以在这个 get 函数中执行第一段代码吗? 我的意思是,我可以在 app.get() 中使用 app.use() 吗?因为我希望来自路径“/img”的请求以数组形式发送到路径“/stats/paths/recent”。
最佳答案
将 app.use
放在 app.get
中是不正确的,因为中间件应该定义一次,而不是在每次请求时定义。
如果打算在同一请求中执行的中间件之间交换数据,它们应该通过 response object 进行通信:
res.locals
An object that contains response local variables scoped to the request, and therefore available only to the view(s) rendered during that request / response cycle (if any). Otherwise, this property is identical to app.locals.
This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on.
即一个数组可以分配给 res.locals.recentPaths
中间件并在另一个中间件中读取。这种情况的问题是 /img
和 /stats/paths/recent
中间件没有在同一个请求中执行。
将数据存储到 recentPaths
变量是不正确的,因为它在请求之间持续存在并且对所有用户都是全局的。如果数据应该在请求之间持续存在并且特定于用户,这应该涉及 session 管理,更好的存储数据的地方是数据库,而不是变量。
关于javascript - 我可以在 app.get 中使用不同路径的 app.use,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54100622/