建议的小程序版本的axios函数,之因此说简易,由于只是用了经常使用的请求方法外,而后添加了拦截器而已。
具体以下:ios
npm i cdd-lib
es6:git
import {wxhttp} from 'cdd-lib'
commonjs:es6
let {wxhttp} = require('cdd-lib')
命名为wxhttp
npm
具体的请求用法如axiosaxios
wxhttp#request(config)小程序
wxhttp#get(url[,config])promise
wxhttp#delete(url[,config])并发
wxhttp#head(url[,config])函数
wxhttp#options(url[,config])post
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方法来进行并发请求。
查看源码