axios,拦截器,封装

一.Axios基本用法

安装

 npm install axios --save

axios跨域解决

第一步:config中index.js中配置

   proxyTable: {
		 '/yizhan': {
		     target: 'https://m.1zhanche.com',
		     changeOrigin: true,
		     pathRewrite: {
		       '^/api': ''
		     }
		   },
			'/top': {
					target: 'https://www.apiopen.top',
					changeOrigin: true,
					     pathRewrite: {
					       '^/top': ''
					     }
			},
			'/damai': {
					target: 'http://www.web520.xyz/web-projectAPI/index.php',
					changeOrigin: true,
					     pathRewrite: {
					       '^/damai': ''
					     }
			}
	},

第二步:使用

let dataParam = {
    start:10,
    count:10
}
axios.get('/api/v2/movie/top250',{
  params: {
    ...dataParam,
  }
})
.then(function (res) {
  console.log(res.data)
})
let dataP = {
  q:"挪威的森林"
}
axios.get('/api/v2/book/search',{
  params: {
    ...dataP,
  }
})
.then(function (res) {
  console.log(res.data)
})

二.封装api

形式1:

import axios from 'axios'
axios.interceptors.request.use(function (config) {
  console.log("a")
  return config;
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});
axios.interceptors.response.use(function (response) {
  console.log("b")
  return response;
}, function (error) {
  // 对响应错误做点什么
  return Promise.reject(error);
    });
 //page=1
	export const femaleNameApi = function (paramsData) {
	  return axios
	    .get('/top/femaleNameApi',{
	      params: {
	        ...paramsData,
	      }
	    })
	    .then(res=>res.data)
	}
	//name
	export const searchMusic = function (paramsData) {
	  return axios
	    .get('/top/searchMusic',{
	      params: {
	        ...paramsData,
	      }
	    })
	    .then(res=>res.data)
	}

调用api

import {getBook,getMovies} from './api/api'
created:function () {
      let dataParam = {
          start:10,
          count:10
      }
      getMovies(dataParam).then((data)=>{
        console.log(data)
      })
      let dataP = {
        q:"村上春树",
        count:10,
        start:10
      }
    getBook(dataP).then((data)=>{
      console.log(data.books)
    })
}

形式2:使用promise封装axios

import axios from 'axios';
    import router from '../router'; 
    axios.defaults.timeout = 100000;
    /*const apiUrl = 'http://shopping.zhongguotengcha.com';*/
    const apiUrl = 'http://vinetea.weibeicc.com';
    
    axios.interceptors.request.use(
      (config) => {
        let pathUrl = [
          '/index/login_with_pwd',
          '/index/login_with_msgCode',
          '/mobileCode/send_mobile_code',
          '/index/register',
          '/mobileCode/check_code_no_login',
          '/index/reset_loginPwd',
        ];
        const token = JSON.parse(window.localStorage.getItem('token')) || '';
        if (!pathUrl.some((it) => config.url.endsWith(it))) {
          if (token) {
            config.headers['Authorization'] = `${token}`;
          }
        }
        return config;
      },
      function(error) {
        // Do something with request error
        return Promise.reject(error);
      }
    );
    
    axios.interceptors.response.use(
      function(response) {
        if (!response.config.url.endsWith('/user/get_user_by_token')) {
          // Do something with response data
          if (response.data.code === 403) {
            router.push({ path: '/login' });
          }
        }
        return response;
      },
      function(error) {
        // Do something with response error
        return Promise.reject(error);
      }
    );
    
    const axiosPost = (url, params = {}) => {
      return new Promise((resolve, reject) => {
        axios
          .post(apiUrl + url, params)
          .then(
            (response) => {
              resolve(response.data);
            },
            (err) => {
              reject(err);
            }
          )
          .catch((error) => {
            reject(error);
          });
      });
    };
    
    const axiosGet = (url, params = {}) => {
      return new Promise((resolve, reject) => {
        axios
          .get(apiUrl + url, {
            params: params,
          })
          .then(
            (response) => {
              resolve(response.data);
            },
            (err) => {
              reject(err);
            }
          )
          .catch((error) => {
            reject(error);
          });
      });
    };
    
    export default {
      get: axiosGet,
      post: axiosPost,
    };

二.使用
方法1:
1.main.js

import ajax from "./data/api.js"
Vue.prototype.$ajax = ajax;

2.app.vue

let params = {
		page:1
}
this.$ajax.get("/top/femaleNameApi",params).then((res)=>{
		console.log(res);
})

形式3:加入await和ansyc的使用
1.main.js

import ajax from "./data/api.js"
Vue.prototype.$ajax = ajax;

2.app.vue

created:async function(){
let params = {
page:1
}
await this.femaleNameApi(params);
},
methods:{
async femaleNameApi(params){
let res = await this.$ajax.get("/top/femaleNameApi",params);
console.log(res.data);
}
}

你可能感兴趣的:(vue)