axios/Fetch通讯解决方案

443 阅读2分钟
  1. 安装 axios、qs
npm install qs axios --save
  1. src目录下新建http.js
  • axios
import axios from "axios";
import store from "@/store";
import { MessageBox, Message } from "element-ui";
import qs from "qs";
import { isPlainObject } from '@/utils'
import { getToken } from "@/utils/auth";

// 请求设置
const service = axios.create({
  baseURL: '', // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 99999 // 设置请求超时时间
})

// 请求拦截器
service.interceptors.request.use((config) => {
  // headerType 1 formdata 2 json
  if (config.headerType === 1) {
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    config.data = qs.stringify(config.data)
  } else {
    config.headers['Content-Type'] = 'application/json;charset=UTF-8'
    if (isPlainObject(config.data)) qs.stringify(config.data)
  }
  // 针对于部分接口,我们不携带令牌和签名信息
  const apiList = [
    '/login',
    '/captchaImage',
  ]
  // 如果请求地址去掉/api是apiList所包含的接口
  if (
    !apiList.includes(config.url.replace(process.env.VUE_APP_BASE_API, '')) &&
    getToken()
  ) {
    
    // 在发送请求之前做些什么 Authorization
    config.headers['Authorization'] = getToken()
  }
  return config
},
  (error) => {
    // 处理请求错误
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  // 业务逻辑错误
  (response) => {
    const res = response.data;
    // 接口如果code返回不为200,即为错误。
    if (res.code !== 200) {
      Message({
        message: res.msg || "Error",
        type: "error",
        duration: 3 * 1000,
      });

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        // to re-login
        MessageBox.confirm(
          "登录状态已过期,您可以继续留在该页面,或者重新登录",
          "系统提示",
          {
            confirmButtonText: "重新登录",
            cancelButtonText: "取消",
            type: "warning",
          }
        ).then(() => {
          store.dispatch("user/resetToken").then(() => {
            location.reload();
          });
        });
      }
      return Promise.reject(new Error(res.msg || "Error"));
    } else {
      return res;
    }
  },
  (error) => {
    console.log("err" + error); // for debug
    Message({
      message: error.msg,
      type: "error",
      duration: 3 * 1000,
    });
    return Promise.reject(error);
  }
);

export default service;
  • Fetch
import qs from 'qs';
const isPlainObject = function isPlainObject(obj) {
    let proto, Ctor;
    if (!obj || Object.prototype.toString.call(obj) !== "[object Object]") return false;
    proto = Object.getPrototypeOf(obj);
    if (!proto) return true;
    Ctor = proto.hasOwnProperty('constructor') && proto.constructor;
    return typeof Ctor === "function" && Ctor === Object;
};

let baseURL = 'http://127.0.0.1:9999',
    inital = {
        method: 'GET',
        params: null,
        body: null,
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    };

export default function request(url, config) {
    if (typeof url !== "string") throw new TypeError('url must be required!');
    if (!isPlainObject(config)) config = {};
    if (config.headers) {
        if (!isPlainObject(config.headers)) config.headers = {};
        config.headers = Object.assign({}, inital.headers, config.headers);
    }
    let {
        method,
        params,
        body,
        headers
    } = Object.assign({}, inital, config);

    // 处理URL
    if (!/^http(s?):\/\//i.test(url)) url = baseURL + url;
    if (params != null) {
        if (isPlainObject(params)) params = qs.stringify(params);
        url += `${url.includes('?')?'&':'?'}${params}`;
    }

    // 处理请求主体
    let isPost = /^(POST|PUT|PATCH)$/i.test(method);
    if (isPost && body != null && isPlainObject(body)) {
        body = qs.stringify(body);
    }

    // 发送请求
    config = {
        method: method.toUpperCase(),
        headers
    };
    if (isPost) config.body = body;
    return fetch(url, config).then(response => {
        // 只要服务器有返回值,则都认为promise是成功的,不论状态码是啥
        let {
            status,
            statusText
        } = response;
        if (status >= 200 && status < 300) {
            // response.json():把服务器获取的结果变为json格式对象,返回的一个promise实例
            return response.json();
        }
        return Promise.reject({
            code: 'STATUS ERROR',
            status,
            statusText
        });
    }).catch(reason => {
        // @1 状态码错误
        if (reason && reason.code === "STATUS ERROR") {
            // ...
        }

        // @2 断网
        if (!navigator.onLine) {
            // ...
        }

        return Promise.reject(reason);
    });
};
  1. src目录下新建index.js 可以不同页面的接口写在不同的js文件中,按照模块划分,导入到index.js中
import axios from './http';
import request from './http2';

function getList(options={}){
    options = Object.assign({
        src: 'web',
        alist: '',
        pageNum: 1
    })
}

const queryUserInfo = userId => {
    /*  return axios.get('/user/info', {
         params: {
             userId
         }
     }); */
    return request('/user/info', {
        params: {
            userId
        }
    });
};

const setUserLogin = (account, password) => {
    /* return axios.post('/user/login', {
        account,
        password
    }); */
    return request('/user/login', {
        method: 'POST',
        body: {
            account,
            password
        }
    });
};

export default {
    queryUserInfo,
    setUserLogin
};
  1. main.js引用
import Vue from 'vue';
import App from './App.vue';
import api from './api/index';

Vue.config.productionTip = false;
Vue.prototype.$api = api;

new Vue({
  render: h => h(App)
}).$mount('#app');

/*
   $.ajax  导入JQ   基于回到函数管理的
       $.ajax({
          url:'/api/list',
          success(result){
              
          }
       });
   axios 下载安装这个模块   基于Promise封装的ajax库
       axios.get('/api/list').then(result=>{
          return axios.get('/api/info');
       }).then(result=>{
          
       });
   ------上述两种办法都是基于 XMLHttpRequest 方案完成的

   fetch 直接用(ES6),本身就是基于Promise管理的,和XMLHttpRequest没有任何关系,是浏览器新提供的一种前后端数据通信方案
    https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch
 */
  1. 页面引用
methods: {
    // 请求数据
    async getData(){
        this.loading = true 
        let { d, s } = await this.$api.homeList.getList({
            pageNum: 1,
            alias: ""
        })
        this.loading = false
        // 验证状态码
        if(s == 1){
            // 数据是否不为空
            if(d && d.length>0){
                // 长列表渲染优化
                d = d.map(item => Object.freeze(item))
                // concat不能重新渲染
                this.source.push(...d)
                return
            }
            // 加载完毕
            this.fiinished = true
        }
    },
    // 加载更多数据
    async loadMore() {
        this.pageNum += 1
        await this.querData()
    }
}