基於 axios 體驗的微信小程序請求工具,徹底使用Promise,並提供了請求和響應的攔截。html
gihub地址:github.com/hotpotLeo/d…ios
gitee地址:gitee.com/DocBug/dov-…git
import dov from './libs/dov.min.js'
// http.js
import dov from './libs/dov.min.js'
dov.get('http://www.baidu.com/user').then(response => {
console.log(response)
})
// 或者
dov.defaults.baseURL = 'http://www.baidu.com' // 設置默認地址
dov.get('http://www.baidu.com/user').then(response => {
console.log(response)
})
複製代碼
第二個參數能夠追加參數github
dov.get('http://www.baidu.com/user', {
data: {
username: 'dov',
password: 'asdkln211232345sa'
}
}).then(response => {
console.log(response)
})
複製代碼
多個請求合併npm
function getUserInfo(){
return dov.get('/userinfo')
}
function getUserPerssion(){
return dov.get('/userPerssion')
}
dov.all([getUserInfo(), getUserPerssion()]).then(response => {
console.log(response)
}).catch(error => {
console.log(error)
})
複製代碼
dov(config)axios
dov({
method: 'post',
url: 'http://www.baidu.com/getUserInfo',
data: {
username: 'king',
password: 'kingpassword'
}
}).then(response => {
console.log(response)
})
// 或
dov.defaults.baseURL = 'http://www.baidu.com'
dov({
method: 'post',
url: '/getUserInfo',
data: {
username: 'king',
password: 'kingpassword'
}
}).then(response => {
console.log(response)
})
複製代碼
dov.(url[,config])小程序
dov('http://www.baidu.com/getUserInfo', {
method: 'post',
data: {
username: 'king',
password: 'kingpassword'
}
}).then(response => {
console.log(response)
})
複製代碼
小程序中定義了8種請求類型:微信小程序請求方式微信小程序
可能須要多個實例來操做時,能夠經過 create 方法來實現。api
let server1 = dov.create({
baseURL: 'https://api.baidu.com'
})
let server2 = dov.create({
baseURL: 'https://img.baidu.com'
})
server1.get('/getUserInfo').then(response => {
console.log(response)
})
複製代碼
{
baseURL: '', // 默認地址
url: '',
data: {},
header: {},
method: '',
dataType: '',
responseType: '',
}
複製代碼
dov 也提供了和 axios 同樣的請求攔截和響應攔截,而且能夠配置多個
// 1.第一個 request 的攔截器
dov.interceptors.request.use(function (config) {
config.data.header['Authorization'] = wx.getStorageSync('token')
// ...
return config
})
// 2.第二個 request 的攔截器,
dov.interceptors.request.use(function (config) {
config.data.token = wx.getStorageSync('token')
// ...
return config
})
複製代碼
// 1.第一個 response 的攔截器
dov.interceptors.response.use(function (response) {
if (response.status === 200) {
...
}
return response
})
// 2.第二個 response 的攔截器,
dov.interceptors.response.use(function (response) {
if (response.status === 300) {
...
}
return response
})
複製代碼
MIT