axios的基本使用
// get 请求
axios.get('api/index.json',{
params: {}
}).then(res => {}).catch(err => {})
// post 请求
axios.post('/api/getUserInfo', {
data: {}
}).then(res => {}).catch(err => {})
// 并发请求
axios.all([
axios.get('/api/index.json'),
axios.get('/api/getUser.json')
]).then(axios.spread((indexJson, userJson) => {
// indexJson 第一个接口返回的数据
// userJson 第二个接口返回的数据
})
)
axios的全局配置
axios.defaults.timeout = 1000
axios 实例配置
let instance = axios.creat({
timeout: 1000, // 请求的超时时长
baseURL: 'http://localhost:8080', // 请求的基本域名地址
url: '/api/getUser', // 请求地址
data: {}, // post请求入参
params: {}, //get 请求入参
headers: {} // 设置请求头
})
axios 拦截器
// 请求拦截器
let instance = axios.interceptors.request.use(config => {
// 请求前做些什么
return config
}, err => {
return Promise.reject(err)
})
// 响应拦截器
let instance = axios.interceptors.response.use(res => {
// 响应成功对数据做些什么
return res
}, err => {
return Promise.reject(err)
})
// 取消拦截器 (一般不用)
axios.interceptors.request.eject(instance)
取消请求
let source = axios.CancelToken.source()
axios.get('/index.json', {
cancelToken: source.token
}).then(res => {
console.log(res)
}).catch(err => {
console.log(err)
})
// source.cancel(message) 参数message 可选填
source.cancel('http get cancel')
axios 的封装
import axios from 'axios'
import { baseURL } from '@/config/index.js'
class HttpRequest {
constructor (baseUrl = baseURL) {
this.baseUrl = baseUrl
// 队列
this.query = {}
}
// 全局参数
getinSidConfig () {
const config = {
baseUrl: this.baseUrl,
headers: {}
}
return config
}
// 请求方法
request (options) {
const instance = axios.create()
options = Object.assign(this.getinSidConfig(), options)
this.interceptors(instance, options.url)
return instance(options)
}
// 拦截器
interceptors (instance, url) {
instance.interceptors.request.use(config => {
// 使用队列的方式处理如果是第一个到最后一个请求了则增加loding
// 以防出现多个loding层样式错误
if (!Object.keys(this.query).length) {
// Spin.show()
}
this.query[url] = true
return config
}, err => {
return Promise.reject(err)
})
instance.interceptors.response.use(res => {
delete this.query[url]
const {data, status} = res
return {data, status}
}, err => {
return Promise.reject(err)
})
}
}
export default HttpRequest
// 用法
import axios from './index'
export const getUserInfo = () => {
return axios.request({
url: '/getUserInfo',
methods: 'get'
})
}
// home.vue
created () {
getUserInfo().then(res => {
console.log(res)
})
}