js-request
介绍
基于 JS 实现的前后端(browser and node)共用请求模块
代码冗余,故从https://gitee.com/DieHunter/utils-lib-js中分离
博客介绍
https://hunter1024.blog.csdn.net/article/details/126719561
使用说明
- 使用 pnpm i utils-lib-js 安装工具包依赖(二选一)
- 使用 pnpm i js-request-lib 安装请求依赖(二选一)
- 使用 pnpm debug 进行源码调试
- 在代码中引入 js-request-lib 模块, 创建一个请求实例
import { Request } from "../dist/esm/index.js";
const request = new Request("https://www.xxx.com");
- 使用 GET 方法发起一个简单的请求:
request
.GET("/users", { page: 1, limit: 10 })
.then((response) => {
console.log("GET 请求成功", response);
})
.catch((error) => {
console.error("GET 请求失败", error);
});
- 发起 POST 请求
const requestBody = { username: "hunter", password: "secret" };
request
.POST("/login", null, requestBody)
.then((response) => {
console.log("POST 请求成功", response);
})
.catch((error) => {
console.error("POST 请求失败", error);
});
- 除了 GET 和 POST,该工具类还支持其他请求方法,例如 PUT、DELETE、OPTIONS、HEAD 和 PATCH。使用方式相似,只需调用相应的方法:
request
.PUT("/users/1", null, { name: "hunter" })
.then((response) => {
console.log("PUT 请求成功", response);
})
.catch((error) => {
console.error("PUT 请求失败", error);
});
- 拦截器,通过拦截器,你可以在请求中添加额外的头部信息、处理响应数据
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;
});
- 在创建请求实例时设置其他配置,例如设置超时时间、自定义请求头等:
const customRequest = new Request("https://api.example.com", {
timeout: 5000,
headers: {
Authorization: "Bearer YOUR_ACCESS_TOKEN",
"Content-Type": "application/json",
},
});
customRequest
.GET("/data")
.then((response) => {
console.log("请求成功", response);
})
.catch((error) => {
console.error("请求失败", error);
});
参与贡献
- Fork 本仓库
- Star 本仓库
- 提出建议
- 新建 Pull Request