建議的小程序版本的axios函數,之所以說簡易,因爲只是用了常用的請求方法外,然後添加了攔截器而已。
具體如下:
wxhttp
命名爲wxhttp
具體的請求用法如axios
wxhttp#request(config)
wxhttp#get(url[,config])
wxhttp#delete(url[,config])
wxhttp#head(url[,config])
wxhttp#options(url[,config])
wxhttp#post(url[,data[,config]])
wxhttp#put(url[,data[,config]])
wxhttp#patch(url[,data[,config]])
攔截方法:
- 請求攔截
wxhttp.interceptors.request.use(handleRequest(config),handleError(err))
注意:handleRequest需要返回處理後的config
- 返回攔截
wxhttp.interceptors.response.use(handresponse(res))
注意:handleResponse需要返回處理後的res
例子:
import $http from "../../utils/http"
export default {
name: 'seckillHome',
data() {
return {
}
},
onShow() {
// 請求攔截
$http.interceptors.request.use(function (config) {
console.log(`請求攔截`, config)
// 此處設置的數據將與請求的數據進行合併,如果自動同名則以攔截的爲準。
config.data = {
address: "北京市東城區"
}
return config
})
$http.post('https://www.baidu.com', {
name: 'cdd',
age: 23
}).then(res => {
console.log(`結果是`, res)
})
}
}
因爲使用了promise風格,所以可以使用Promise.all方法來進行併發請求。
查看源碼