用法
axios({
method: 'get', // post、get、put、delete....
baseURL: '', // 请求的域名,基本地址,公共的路径
url: '', // 请求的路径
params: {}, // get参数会将请求参数拼接在url上
data: {}, // post会将请求参数放在请求体中
headers: {}, // 设置请求头,例如设置token等
timeout: 1000, // 设置请求超时时长,单位:ms
withCredentials:default,//表明了是否是跨域请求、默认是default
maxContentLength:1000//相应内容的最大值
})
其他写法 注:参数带[]表示不是必填参数,没有[]表示是必填参数
axios.request(config)
axios.get(url, [config])
axios.post(url, [data], [config]])
axios#delete(url[, config])
配置默认值
1、全局配置baseURL[URL三个字母必须大写,不然axios不认]
axios.defaults.baseURL = '公共路径';
如:axios.defaults.baseURL = 'https://baidu.com';
axios.defaults.timeout = 1000;
在实际项目中,很少用全局配置。
2、实例配置
const instance = axios.create({
baseURL: 'http://localhost:8888/api/private/v1/',
timeout: 1000,
})
//方法一
instance.get('/getUserInfo').then(res => {
// ...
})
//方法二
axios.defaults.baseURL = 'http://localhost:8888/api/private/v1/';
getright() {
return axios.get("rights/list").then(res=>{})
},
3、请求配置
//方法一
const instance = axios.create();
instance.get('/getUserInfo', {
timeout: 5000
})
//方法二
install(Vue) {
// 将axios添加到vue.prototype上
Vue.prototype.$getright = getright;
}
-----------------------------------
注:配置的优先顺序
全局 < 实例 < 请求
并发处理[一个页面请求多个接口]
同时进行多个请求,并统一处理返回值
axios.all(iterable)
axios.spread(callback)
例:
axios.all([
axios.post('/addusers',{name:'yannn',age:22}),
axios.detete('/delete',{id:2})
]).then(axios.spread((add, del) => {
console.log(add, del);
}))
总结
上面是总结的较为常用的参数配置和axios请求的使用方式,希望对你有用~~~~