anyup design
一个基于 promise 的,轻量且强大的 http 网络库
🔥 文档网站
简介
🚀 基于 promise
的 uni.request
,轻量且强大的 http
网络库:
- 提供统一的
Promise API
。 - 浏览器环境下,轻量且非常轻量 。
- 基于
uni.request
,支持多种运行环境。 - 支持请求/响应拦截器。
- 自动转换
JSON
数据。 - 支持批量生成API请求,简化代码量99%,一行代码搞定
安装
// 安装
npm install @anyup/uni-http -S
// 更新
npm update @anyup/uni-http
复制代码
一、快速上手
import { Http } from '@/uniui/index.js'
const http = new Http().setBaseURL('').setHeader({ 'Content-Type': 'application/json;charset=UTF-8' })
// 请求示例
requestLogin(username, password) {
http.request('/login', { username, password }).then(res => {
})
}
// es6 await风格
async requestLogin(username, password) {
await http.request('/login', { username, password })
}
// 上传文件示例,上传文件封装的uni.uploadFile
async uploadFile() {
await http.upload('/upload', { filePath: 'file', , name: 'fileName', formData: {} } )
}
复制代码
二、进阶,按需批量生成API,体验飞一般的感觉
1.初始化 Http 类
// http.js
import { Http } from '@/uniui/index.js'
const header = {}
const baseURL = ''
const http = new Http().setBaseURL(baseURL).setHeader(header)
// 请求拦截器
http.interceptors.request.use(
request => {
if (request.loading) {
// 如果配置了loading,显示
}
// 设置请求header
request.header['Authorization'] = ''
return request
},
error => Promise.resolve(error)
)
// 响应拦截器
http.interceptors.response.use(
response => {
// 请求成功
if (!response.data) {
return Promise.reject(new Error('接口请求未知错误'))
}
// 其他业务处理
return Promise.resolve(response)
},
error => {
// 请求失败,业务处理
return Promise.reject(error)
},
complete => {
// 请求完成
if (complete.request.loading) {
// 如果配置了loading,关闭
}
// 其他业务处理
console.log('complete', complete)
}
)
export default new Http.Builder(http)
复制代码
2.定义接口配置
// api.js
import http from './http'
const urls = {
// 用户
login: { url: '/api/login', method: 'POST', loading: true } // 用户登录
}
export default http.dispatch(urls)
复制代码
3.使用方式
// demo.vue
<script>
import api from './api'
export default {
methods: {
login() {
api.login().then(res => {
// 请求成功
})
}
}
}
复制代码
浏览器支持
支持现代浏览器以及 Android >= 4.0、iOS >= 8.0。