js-request-lib
TypeScript icon, indicating that this package has built-in type declarations

1.0.10 • Public • Published

js-request

介绍

基于 JS 实现的前后端(browser and node)共用请求模块 代码冗余,故从https://gitee.com/DieHunter/utils-lib-js中分离

博客介绍

https://hunter1024.blog.csdn.net/article/details/126719561

使用说明

  1. 使用 pnpm i utils-lib-js 安装工具包依赖(二选一)
  2. 使用 pnpm i js-request-lib 安装请求依赖(二选一)
  3. 使用 pnpm debug 进行源码调试
  4. 在代码中引入 js-request-lib 模块, 创建一个请求实例
import { Request } from "../dist/esm/index.js";
const request = new Request("https://www.xxx.com");
  1. 使用 GET 方法发起一个简单的请求:
request
  .GET("/users", { page: 1, limit: 10 })
  .then((response) => {
    console.log("GET 请求成功", response);
  })
  .catch((error) => {
    console.error("GET 请求失败", error);
  });
  1. 发起 POST 请求
const requestBody = { username: "hunter", password: "secret" };

request
  .POST("/login", null, requestBody)
  .then((response) => {
    console.log("POST 请求成功", response);
  })
  .catch((error) => {
    console.error("POST 请求失败", error);
  });
  1. 除了 GET 和 POST,该工具类还支持其他请求方法,例如 PUT、DELETE、OPTIONS、HEAD 和 PATCH。使用方式相似,只需调用相应的方法:
// 发起 PUT 请求
request
  .PUT("/users/1", null, { name: "hunter" })
  .then((response) => {
    console.log("PUT 请求成功", response);
  })
  .catch((error) => {
    console.error("PUT 请求失败", error);
  });
  1. 拦截器,通过拦截器,你可以在请求中添加额外的头部信息、处理响应数据
// 添加请求拦截器
request.use("request", (config) => {
  // 在请求发送前执行逻辑
  console.log("请求拦截器 - 请求发送前", config);
  return config;
});

// 添加响应拦截器
request.use("response", (response) => {
  // 在响应处理后执行逻辑
  console.log("响应拦截器 - 响应处理后", response);
  return response;
});
// 添加错误拦截器
request.use("error", (err) => {
  // 在出错时执行逻辑
  console.log("出错 - 处理后", err);
  return err;
});
  1. 在创建请求实例时设置其他配置,例如设置超时时间、自定义请求头等:
const customRequest = new Request("https://api.example.com", {
  timeout: 5000, // 设置超时时间为 5 秒
  headers: {
    Authorization: "Bearer YOUR_ACCESS_TOKEN", // 设置自定义请求头
    "Content-Type": "application/json",
  },
});

customRequest
  .GET("/data")
  .then((response) => {
    console.log("请求成功", response);
  })
  .catch((error) => {
    console.error("请求失败", error);
  });

参与贡献

  1. Fork 本仓库
  2. Star 本仓库
  3. 提出建议
  4. 新建 Pull Request

Package Sidebar

Install

npm i js-request-lib

Weekly Downloads

76

Version

1.0.10

License

ISC

Unpacked Size

83.5 kB

Total Files

17

Last publish

Collaborators

  • diehunter