You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Express响应缓存中间件TypeScript类型定义问题求助

Express响应缓存中间件TypeScript类型问题解决

方案一:修正res.send的类型匹配

Express的res.send方法要求返回Response对象,你的原实现返回void导致类型不兼容,只需让重写的函数返回原send方法的调用结果即可解决:

import { Request, Response, NextFunction, Send } from 'express'
import NodeCache from 'node-cache'
const myCache = new NodeCache({ stdTTL: 60 * 5 })

const cache = (req: Request, res: Response, next: NextFunction) => {
  const key = '__express__' + (req.originalUrl || req.url)
  const cachedBody: string | undefined = myCache.get(key)
  
  if (cachedBody) {
    return res.send(cachedBody)
  } else {
    // 显式声明sendResponse的类型为Send,绑定this指向res
    const sendResponse: Send<Response> = res.send.bind(res)
    
    res.send = (body) => {
      myCache.set(key, JSON.stringify(body))
      // 返回原send方法的调用结果,匹配Response类型要求
      return sendResponse(body)
    }
    next()
  }
}

方案二:通过响应finish事件缓存(更安全)

重写res.send可能与其他中间件产生冲突,监听finish事件是更稳妥的方案,响应完成后再缓存响应体:

import { Request, Response, NextFunction } from 'express'
import NodeCache from 'node-cache'
const myCache = new NodeCache({ stdTTL: 60 * 5 })

const cache = (req: Request, res: Response, next: NextFunction) => {
  const key = '__express__' + (req.originalUrl || req.url)
  const cachedBody: string | undefined = myCache.get(key)
  
  if (cachedBody) {
    return res.send(cachedBody)
  } else {
    const originalSend = res.send
    let responseBody: any
    
    // 临时重写send捕获响应体,保持原方法的返回类型
    res.send = function(body) {
      responseBody = body
      return originalSend.call(this, body)
    }
    
    // 响应完成后执行缓存操作
    res.on('finish', () => {
      if (responseBody) {
        myCache.set(key, JSON.stringify(responseBody))
      }
    })
    
    next()
  }
}

内容的提问来源于stack exchange,提问作者tomblixt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 11:40:21