1.对axios进行二次封装,创建api文件,然后创建request.js,设置请求拦截器和响应拦截器

// 对axios进行二次封装
import axios from 'axios'
import { config } from 'vue/types/umd';

// 利用axios里面的creat方法对axios进行二次封装

const request = axios.create({
    // 配置对象
    baseURL:"/api",
    timeout:5000,//超时的时间
});
// 请求拦截器,不能随便请求,请求的时候会检测到

requests.interceptors.request.use(()=>{
    // config:配置对象,header请求头
    return config;
});

// 响应拦截器,服务端响应数据回来以后,响应拦截器可以检测到,可以做一些事情
requests.interceptors.response.use((res)=>{
    return res.data();
},(error)=>{
// 响应失败的回调函数
return Promise.reject(new Error('faile'));
});

2.创建index.js文件,api接口统一管理:1.项目较小,可以在组件的生命周期里面发送请求

                                                    2.项目较大,接口函数统一管理,将每一个请求放到这个文件里面

//api/index.js
// 当前这个模块:API模块
import requests from './request';


// 三级联动接口
// api/product/getBaseCategoryList  get   无参数

// 暴露api函数,请求三级联动
export const reqCategoryList=()=>{
    // 调用request,baseUrl已经将api
    requests({url:'/product/getBaseCategoryList',method:'get'})
}

3.解决跨域问题,jsp,代理服务器,CORS

vue里面使用代理服务器,配置代理服务器

 devServer: {
    // 配置代理服务器
    proxy: {
      '/api': {
        target: '<url>',
        ws: true,
        changeOrigin: true
      },
    }
  }
})

4. ①对api接口的统一封装,将api加在vue的原型上面

//main.js
 beforeCreate()
  {
    // 设置全局事件总线
     Vue.prototype.$bus = this;
    //  统一封装api接口
    Vue.prototype.$API = API;
    // 引入弹框组件
    Vue.prototype.$msgbox = MessageBox
    Vue.prototype.$alert = MessageBox.alert
  },

    ②使用的时候可以直接this.$API.请求函数

 let res = await this.$API.reqSubmitOrder(tradeNO,data);

Logo

前往低代码交流专区

更多推荐