MST

星途 面试题库

面试题:Node.js缓存中间件基础使用

请简述在Node.js项目中,如何使用常见的缓存中间件(如express - cache - response)来缓存API响应?并说明在缓存时,如何处理动态路由参数的情况,以确保缓存的准确性。
18.2万 热度难度
前端开发Node.js

知识考点

AI 面试

面试题答案

一键面试
  1. 使用express - cache - response缓存API响应
    • 安装依赖:首先在Node.js项目中通过npm install express - cache - response安装该中间件。
    • 引入并使用中间件:在Express应用中引入该中间件,示例代码如下:
const express = require('express');
const cache = require('express - cache - response');
const app = express();

// 设置缓存时间为1小时(3600秒)
const oneHour = 3600;
app.get('/api/data', cache({
    statusCode: 200,
    duration: oneHour
}), (req, res) => {
    // 这里是处理API请求的逻辑,例如从数据库获取数据
    res.json({ message: 'Cached API response' });
});
  1. 处理动态路由参数确保缓存准确性
    • 不缓存含动态参数的请求:如果动态路由参数对响应影响较大,可选择不缓存包含动态路由参数的请求。例如,对于/api/user/:userId这样的路由,可以不应用缓存中间件。
    • 按参数缓存:若要缓存不同参数的响应,可以根据参数生成唯一的缓存键。例如,对于/api/post/:postId路由:
app.get('/api/post/:postId', cache({
    statusCode: 200,
    duration: oneHour,
    generateKey: (req) => `/api/post/${req.params.postId}`
}), (req, res) => {
    // 根据postId从数据库获取对应文章数据并返回
    res.json({ post: '文章内容' });
});

这样每个不同postId的请求会有单独的缓存,确保缓存的准确性。