首页 > web前端 > js教程 > @rxliuli/vista 简介:一个用于 Fetch 和 XHR 的统一请求拦截器库,具有中间件支持。

@rxliuli/vista 简介:一个用于 Fetch 和 XHR 的统一请求拦截器库,具有中间件支持。

Patricia Arquette
发布: 2025-01-07 00:19:40
原创
729 人浏览过

Introduction to @rxliuli/vista: A unified request interceptor library for both Fetch and XHR with middleware support.
Introduction to @rxliuli/vista: A unified request interceptor library for both Fetch and XHR with middleware support.

@rxliuli/vista是一个强大的同构请求拦截器库,支持Fetch/XHR请求的统一拦截。它允许您在请求生命周期的不同阶段进行干预,实现请求监控、修改和模拟等各种功能。

特征

  • ?同时支持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()
登录后复制

API参考

远景级

主拦截器类,提供以下方法:

  • use(middleware): 添加中间件
  • Intercept():开始拦截请求
  • destroy():停止拦截请求

中间件上下文

中间件函数接收两个参数:

  • context:包含请求和响应信息
    • req:请求对象 res:响应对象
    • type:请求类型,fetch或xhr
  • next:调用下一个中间件或原始请求的函数

常问问题

  1. 如何停止拦截?
   const vista = new Vista()
   vista.intercept()
   // When not needed
   vista.destroy()
登录后复制
  1. 是否支持异步操作?
    是的,中间件支持 async/await 语法。

  2. Node.js 中是否支持拦截请求?

不可以,仅支持在浏览器中拦截请求。

谢谢

  • xhook:一个实现xhr拦截的库,有助于一些功能的实现。
  • hono:一个优秀的Web服务器框架,它的API提供了很多灵感。

贡献指南

欢迎提交问题和拉取请求!

执照

麻省理工学院许可证

尝试一下并告诉我您的体验,欢迎任何错误或功能反馈。

以上是@rxliuli/vista 简介:一个用于 Fetch 和 XHR 的统一请求拦截器库,具有中间件支持。的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板