一个基于 promise 的,轻量且强大的 http 网络库
🚀 基于 promise 的 uni.request ,轻量且强大的 http 网络库:
Promise API。uni.request,支持多种运行环境。JSON 数据。// 安装
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: {} } )
}
复制代码
// 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)
复制代码
// api.js
import http from './http'
const urls = {
// 用户
login: { url: '/api/login', method: 'POST', loading: true } // 用户登录
}
export default http.dispatch(urls)
复制代码
// demo.vue