@rxliuli/vista是一个强大的同构请求拦截器库,支持Fetch/XHR请求的统一拦截。它允许您在请求生命周期的不同阶段进行干预,实现请求监控、修改和模拟等各种功能。
npm install @rxliuli/vista # Or yarn add @rxliuli/vista # Or pnpm add @rxliuli/vista
import { Vista } from '@rxliuli/vista' new Vista() .use(async (c, next) => { console.log('Request started:', c.req.url) await next() }) .use(async (c, next) => { await next() console.log('Response data:', await c.res.clone().text()) }) .intercept()
new Vista() .use(async (c, next) => { c.req.headers.set('Authorization', 'Bearer token') await next() }) .intercept()
const cache = new Map() new Vista() .use(async (c, next) => { const key = c.req.url if (cache.has(key)) { c.res = cache.get(key).clone() return } await next() cache.set(key, c.res.clone()) }) .intercept()
new Vista() .use(async (c, next) => { const maxRetries = 3 let retries = 0 while (retries < maxRetries) { try { await next() break } catch (err) { retries++ if (retries === maxRetries) throw err } } }) .intercept()
new Vista() .use(async (c, next) => { await next() if (c.req.url === 'https://example.com/example') { const json = await c.res.json() json.id = 2 c.res = new Response(JSON.stringify(json), c.res) } }) .intercept()
主拦截器类,提供以下方法:
中间件函数接收两个参数:
const vista = new Vista() vista.intercept() // When not needed vista.destroy()
是否支持异步操作?
是的,中间件支持 async/await 语法。
Node.js 中是否支持拦截请求?
不可以,仅支持在浏览器中拦截请求。
欢迎提交问题和拉取请求!
麻省理工学院许可证
尝试一下并告诉我您的体验,欢迎任何错误或功能反馈。
以上是@rxliuli/vista 简介:一个用于 Fetch 和 XHR 的统一请求拦截器库,具有中间件支持。的详细内容。更多信息请关注PHP中文网其他相关文章!