• 大型项目axios封装


    目录结构

    ├─ src   
    |   ├── apis                                    
    |   |   ├── api.js                              // 返回值和错误统一处理 ,  统一管理
    |   |   ├── login.js                            //模块或页面下的请求
    │  ├──request                               // 基本配置
    │  │   ├── service.js                      //统一处理接口 , 拦截 , 状态处理
    │  │   ├── common.js                         //传参处理 
    │  │   ├── apiUrl.js                        //接口url

    service.js

    //统一处理接口 , 拦截 , 状态处理
    import axios from 'axios'
    import {
      BASEURL
    } from './apiUrl'
    //获取token
    function getToken() {
      let token = window.sessionStorage.getItem('token') || ''
      return token;
    }
    
    //创建axios实例
    var serive = axios.create({
      baseURL: BASEURL, // 'https://mock.cangdu.org/mock/5fb233ffbcab7337c1b1c295/example', //请求接口公共部分
      timeout: 5500 //等待时间
    })
    
    //配置默认请求头类型
    serive.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
    serive.defaults.headers.get['Content-Type'] = 'application/json;chartset=utf-8'
    //请求拦截器
    serive.interceptors.request.use(
      config => {
        if (getToken()) {
    //根据实际需求进行请求头设置
          config.headers['token'] = getToken();
          config.headers['Content-Type'] = 'application/json;chartset=utf-8';
        } else { //如果没有登录则跳转登录页
          // routers.push('/login')
        }
        return config
      },
      err => Promise.reject(err)
    )
    //响应拦截器
    serive.interceptors.response.use(
      response => {
        let res = response.data;
    //分别对不同的情况进行处理
        if (res.code == '400') {
        
        } else if (res.code == '401') {
    
        }
        return Promise.resolve(response.data)
      },
      err => Promise.reject(err)
    )
    
    export default serive

    common.js

    //传参处理 细分解藕
    import serive from './service'
    export function requestOfPost(url, data) {
      return serive.post(url, data);
    }
    
    export function requestOfGet(url, data) {
      return serive.get(url, data);
    }

    apiUrl.js

    //接口url , 在编译时会打乱 , 反编译也无法获取 , 安全性提高
    export const BASEURL = 'https://mock.cangdu.org/mock/5fb233ffbcab7337c1b1c295/example';
    export const loginUrl = '/upload';
    export const getUrl = '/query'

    api.js

    //返回值和错误统一处理 , 细分解耦 ,高度封装 , 统一管理
    import {
      requestOfPost,
      requestOfGet
    } from '../request/common.js'
    export function postRequest(url, data) {
      return new Promise((resolve, reject) => {
        requestOfPost(url, data).then(res => resolve(res)).catch(err => reject(err))
      })
    }
    
    export function getRequest(url, data) {
      return new Promise((resolve, reject) => {
        requestOfGet(url, data).then(res => resolve(res)).catch(err => reject(err))
      })
    }

    login.js

    //login接口管理
    import {
      postRequest
    } from './api';
    
    export function loginApi(parmas, callback) {
      postRequest('/upload', parmas, callback)
    }

    如何用?

    举例:

      

    <template>
      <div class="hello">
        <h1>{{ msg }}</h1>
        <h2>Essential Links</h2>
        <button @click="loginHandle">登录</button>
        <button @click="loginHandle2">登录2</button>
        <div class="ddd">123</div>
      </div>
    </template>
    
    <script>
    import { loginUrl, getUrl } from "../request/apiUrl.js";
    import { postRequest, getRequest } from "../api/api.js";
    export default {
      name: "HelloWorld",
      data() {
        return {
          msg: "Welcome to Your Vue.js App",
        };
      },
      methods: {
        async loginHandle() {
          console.log($(".ddd"));
          let params = {
            password: 123456,
            userName: "admin",
          };
          let data = await postRequest(loginUrl, params);
          console.log(data);
        },
        loginHandle2() {
          let params = {
            password: 123456,
            userName: "admin",
          };
          getRequest(getUrl, params).then((res) => console.log(res));
        },
      },
    };
    </script>
    
    
  • 相关阅读:
    SAE/ISO standards for Automotive
    The J1850 Core
    SAE J1708 DS36277 MAX3444, DS75176B
    X431 元征诊断枪
    凯尔卡C68全球版汽车电脑诊断仪
    汽车王牌
    Vehicle’s communication protocol
    Vehicle Network Protocols -- ISO/KWP CAN CCD PCI SCI / SCP / Class 2
    On-board diagnostics -- Standards documents
    On-board diagnostics connector SAE J1962
  • 原文地址:https://www.cnblogs.com/wxyblog/p/13998981.html
Copyright © 2020-2023  润新知