javascript - 我可以在 app.get 中使用不同路径的 app.use

标签 javascript node.js express web backend

我有这段代码获取路径“/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/

相关文章:

javascript - 如果无法连接到服务器,则 Socket.io 客户端触发事件

javascript - 如何在node.js中同步运行这个函数

node.js - 如何在 mongoose 中处理 mongoDB close

node.js - 设置 connect-flash 中间件以供 passport 使用

javascript - 如何在我的网页上设置旋转器/轮播的焦点

javascript - Safari 在我的图像下方显示空白区域?

javascript - 在 React 中显示三个数组中的元素

javascript - 模型属性更新时 UI 不更新,由 knockout ES5 跟踪

node.js - 基于用户角色的中间件返回适当的 HTTP 响应状态代码

javascript - Node.js + Express : How to update page when something has been inserted into database?