axios请求

159 阅读1分钟

首先,写一下export和export default的区别

export的存在:因为一个模块就是一个独立的文件,所以他的内部外部是无法访问的,如果想要获取就必须export抛一下供外部获取。

例子: export var year=1995;import时名字也要是year

export default为默指定输出,可以任意命名

GET方法:

//axios.js

important axios from 'axios';
function myAxios(axiosConfig){
 const service=axios.create({
    baseURL:'http://localhost:8888', //统一的请求前缀
    timeout:1000,
})
   return service(axiosConfig)
}
export default myAxios;//导出myAxios

例子:在别的js请求API

xx.js


important myAxios from './axios'; //引入axios.js文件
 export function getListAPI(paramsList){
  return myAxios({
   url:'/api/list',
   method:'get' //使用get方法
  })

在其他页面触发这个请求

<template> <button @click="getList">点击</button> </template>

<script> 
import {defineComponent} from 'vue' //导入组件
import {getListAPI} from '@/api/xx.js';  //导入js
export default defineComponent({ 
//在页面构建一函数
  setup() {
  function getList() { 
  //得到这个api
    getListAPI().then(res => { 
       console.log(res) 
  }) 
  } 
  return { 
      getList 
      } 
    } 
  }) 
</script>

POST方法:给后端传递参数

import myAxios from './axios';

export function login(paramsList) {
  return myAxios({
    url: '/api/login',
    method: 'post',
    data: paramsList,
    headers:{
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    //在向服务器发送之前对其进行修改
    transformRequest:[
     (data)=>{
      let result=''
      for(let key in data){
       ......
      }
     }
    ]
  });
}

取消重复请求

const pendingMap =new Map();

//生成请求
function getPendingKey(config){
  let {url,method,params,data}=config;
  if(typeof data === 'string') data = JSON.parse(data); 
  // response里面返回的config.data是个字符串对象 
  return [url, method,JSON.stringify(params),JSON.stringify(data)].join('&');             
}

//存储请求
cancel()用于取消请求
function addPending(config){
  //获取这个请求
   const pendingKey=getPendingKey(config); 
   //判断是否重复请求了,如果有就取消,并存入队列
   config.cancelToken = config.cancelToken || new axios.CancelToken((cancel) => {
   if (!pendingMap.has(pendingKey)) {
   pendingMap.set(pendingKey, cancel); 
   } 
   });
}

请求拦截器

//在请求之前先执行存储请求和判断并加入队列
service.intercepetors.request.use(
  config=>{
   addPending(config);
   return config;
  }
  error=>{
  return Promise.reject(error);
  }
)

//响应数据拦截
axios.interceptors.reponse.use(function (response){
   return response;
},function (error){
  //错误的话
  return Promise.reject(error);
}
)

暂时先这么多吧 ,写给自己看的