1.0.0 • Published 1 year ago

sim-k v1.0.0

Weekly downloads
-
License
ISC
Repository
-
Last release
1 year ago

项目描述

从 axios 中获取的灵感,基于 xmlhttprequest 和 fetch 两个 api 封装,支持在不同版本的浏览器自动适配不同的 api,实现了请求和响应的拦截以及动态请求头的添加,支持手动切换 api,支持 promise,支持请求和响应的拦截器,不支持 node 环境

使用

//创建一个sim-k实例
const http = new http();
//设置 底层请求方式 默认根据浏览器版本,可以通过setRunType 设置底层请求方式 目前支持 xhr | fetch

//设置请求方式
http.setRunType("xhr"); //默认更具浏览器版本自动选择

//请求拦截器
http.interceptors.request.use((config) => {
 //所有的请求头配置都在config.headers里面,你可以手动的添加你想要的属性

 //sim-k 和浏览器的版本有关系 高版本的浏览器走fetch,低版本的走XMLHttpRequest

 //例如:  config.headers['token'] = 'token'
 //		 config.withCredentials = true  开启跨域携带cookie
 return config;
});

//相应拦截器
http.interceptors.response.use(
 (response) => {
  //在这里你可以对接口返回的数据做统一的处理

  //注意:error同样会被返回到这里,所以你必须先判断有没有response

  return response;
 },
 (err) => {
  //错误统一拦截
 }
);

//sim-k 目前只有get 和 post两种请求方式

//get请求
http
 .get(url, data)
 .then((response) => {
  console.log(response);
 })
 .catch((err) => {
  console.log(err);
 });
//post请求
http
 .post(url, data)
 .then((response) => {
  console.log(response);
 })
 .catch((err) => {
  console.log(err);
 });
//put请求
http
 .put(url, data)
 .then((response) => {
  console.log(response);
 })
 .catch((err) => {
  console.log(err);
 });
//delete请求
http
 .delete(url, data)
 .then((response) => {
  console.log(response);
 })
 .catch((err) => {
  console.log(err);
 });

//你可以为单独一个请求开启不一样的配置
let config = {
 headers: {
  test: 1,
 },
};
http.get(url, data, config).then((res) => {
 console.log(res);
});

api

方法名称参数备注
setRunType(type:string)'xhr' | ‘fetch’ |‘http’(暂不支持)强制设置请求所使用的 api
setDefaultConfig(config:any)见下表设置请求的默认参数

不同请求 api 支持的 config 属性

Fetch 默认的属性值(config)
url''
baseURL''
timeout5000
mode'cors'
bodyJSON.stringify(config.data)
cache'no-cache'
credentials'same-origin'
headersnew Headers(config.headers)
withCredentialsfalse (credentials = “same-origin”)
XMLHttpRequest 默认的属性值(config)
url''
baseURL''
timeout5000
headersconfig.headers
withCredentialsfalse

浏览器兼容版本

1.0.0

1 year ago