# sim-k **Repository Path**: kang-mou/sim-k ## Basic Information - **Project Name**: sim-k - **Description**: 基于xmlhttprequest和fetch 封装的浏览器请求库 - **Primary Language**: JavaScript - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 1 - **Forks**: 0 - **Created**: 2021-11-18 - **Last Updated**: 2023-04-18 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README ## 项目描述 从 axios 中获取的灵感,基于 xmlhttprequest 和 fetch 两个 api 封装,支持在不同版本的浏览器自动适配不同的 api,实现了请求和响应的拦截以及动态请求头的添加,支持手动切换 api,支持 promise,支持请求和响应的拦截器,不支持 node 环境 ## 使用 ```javascript //创建一个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 | '' | | timeout | 5000 | | mode | 'cors' | | body | JSON.stringify(config.data) | | cache | 'no-cache' | | credentials | 'same-origin' | | headers | new Headers(config.headers) | | withCredentials | false (credentials = “same-origin”) | | [XMLHttpRequest 默认的属性]() | 值(config) | | :---------------------------- | :------------- | | url | '' | | baseURL | '' | | timeout | 5000 | | headers | config.headers | | withCredentials | false | ## 浏览器兼容版本 - [Fetch](https://developer.mozilla.org/zh-CN/docs/Web/API/Headers#%E6%B5%8F%E8%A7%88%E5%99%A8%E5%85%BC%E5%AE%B9%E6%80%A7) - [XMLHttpRequest](https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest#%E6%B5%8F%E8%A7%88%E5%99%A8%E5%85%BC%E5%AE%B9%E6%80%A7)