vue中axios的封装使用

1. vue安装axios

	npm install axios -S
	或者
	npm i axios -S

2. 在main.js进行全局引入

	import axios from 'axios'
	Vue.prototype.$axios = axios  //将axios绑定到vue的原型上

3. 配置跨域 在根目录下vue.config.js里边

	module.exports = {
	    publicPath: './',
	    //配置跨域请求
	    devServer: {
	        open: true,    //是否自动打开浏览器
	        https: false,    //是否开启https
	        hotOnly: false,
	        proxy: { // 配置跨域
	            '/api': {
	                target: 'http://********',   //请求接口域名  
	                ws: true,
	                secure: false,
	                changOrigin: true,    //是否允许跨越
	                pathRewrite: {
	                    '^/api': ''
	                }
	            }
	        },
	        before: app => { }
	    }
	}

4. 在src子目录下的api文件夹下创建request.js文件进行简单的封装axios

	import axios from 'axios'
	import {
	    Message,
	    Loading
	} from "element-ui";
	// 此时需要自行下载一下qs
	import qs from 'qs'
	//判断是否是生产环境
	var isPro = process.env.NODE_ENV === "production" //process.env.NODE_ENV用于区分是生产环境还是开发环境
	//配置不同的baseURL
	// 原理:
    // 在生产环境(给客户部署项目)下使用的是"/weixin-api"(后端给的路径域名后边的部分),此时会自动拿到ip地址 + /weixin-api(路径拼接),在本地跑项目时拿到的时/api 也就是vue.config.js配置跨域下的路径;
    
	let baseURL = isPro ? "/weixin-api" : "/api"
	const service = axios.create({
	    baseURL: baseURL,
	    timeout: 30000 // 请求超时时间
	})
	let loading = "";
	// 请求拦截器
	service.interceptors.request.use(
	    (config) => {
	        // console.log(config)
	        // 在请求发送之前做一些处理
	        if (!(config.headers['Content-Type'])) {
	            loading = Loading.service({
	                lock: true,
	                text: "加载中...",
	                spinner: "el-icon-loading",
	                background: "rgba(255,255,255,0.7)",
	                customClass: "request-loading",
	            });
	            if (config.method == 'post') {
	                config.headers['Content-Type'] =
	                    'application/x-www-form-urlencoded;charset=UTF-8'
	                for (var key in config.data) {
	                    if (config.data[key] === '') {
	                        delete config.data[key]
	                    }
	                }
	                // qs用于序列化data传输的数据 不然后端拿到的话会出现data数据套了一层拿不到数据的问题
	                config.data = qs.stringify(config.data)
	            } else {
	                config.headers['Content-Type'] =
	                    'application/x-www-form-urlencoded;charset=UTF-8'
	                // config.params
	            }
	        }
	        const token = "token"
	        // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
	        if (token) {
	            config.headers['Authorization'] = token
	        }
	        return config
	    },
	    (error) => {
	        loading.close();
	
	        // 发送失败
	        console.log('发送失败', error)
	        return Promise.reject(error)
	    }
	)
	
	// 响应拦截器
	service.interceptors.response.use(
	    (response) => {
	        loading.close();
	        const dataAxios = response.data
	        // 这个状态码是和后端约定的
	        return dataAxios
	    },
	    (error) => {
	        Message({
	            message: error,
	            type: 'error',
	            duration: 3 * 1000
	        })
	        // 如果请求接口失败,取消loading,否则中间有一个接口错误就一直白屏loading转圈;
	        loading.close();
	        return Promise.reject(error)
	    }
	)
	
	export default service

5. 在api文件夹下创建apis文件

//   引入封装好的axios
//   ps:如果没有封装,正常引入axios即可
import axios from "./request";
// 	/api为配置跨域的路径变量
// get请求:
let reportupload= '/report/upload';
export const reportUpload= (params) => {
   return axios.get(reportupload, {
       params: params
   })
}
	// post请求:
let reportupload= '/report/upload';
export const reportUpload= (data) => {
    return axios.post(reportupload, data)
}

6. 在页面中调用接口

	// 引入封装好的接口
 	import { reportUpload } from "@/api/apis.js"; 

	// 调用时使用
    async uploadBackCall() {
     try{
     	let res = await reportUpload();
     	console.log(res)
     }catch{
		// 如果接口请求失败的逻辑回调
	 }finally{}
    },
  • 15
    点赞
  • 46
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 12
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

黑豆1024

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值