vue3 axios使用 配置
1. 第一步肯定是安装 axios: npm install axios --save
2. 创建一个文件输出axios,我这里在src下创建的utils/util.js
3. util.js
import axios from 'axios'const url = process.env.NODE_ENV==='production'? 'http://xxxx.com(线上地址)' : 'http://www.xiongmaoyouxuan.com/api' const $http = axios.create({ baseURL: url, // 所有的请求地址前缀部分 timeout: 60000, // 请求超时时间毫秒 withCredentials: true, // 异步请求携带cookie headers: { // 设置后端需要的传参类型 'Content-Type' : 'application/x-www-form-urlencoded' }, }) // 添加请求拦截器 $http.interceptors.request.use( function (config) { // 设置加载进度 return config }, function (error) {// 发送失败 return Promise.reject(error) } )
// 添加响应拦截器 $http.interceptors.response.use( function (response) { // 关闭加载进度 return response }, function (error) { return Promise.reject(error) } ) const $get = function(url,param,fn){ // get方法 $http.get(url,{params:param}).then(function(res){ fn(res.data) }).catch(function(err){ console.log(err) }) }
const $post = function(url,param,fn){ // post方法 this.$http.post(url,{params:param}).then(function(res){ fn(res.data) }).catch(function(err){ console.log(err); }) }
export{$get, $post,} // 导出方法 4. 页面使用 util.js
aa