preface

Do not recommend complete copy in the past, you can see how I am for my business;

Do an AXIOS package and implementation ideas

Requirements and Implementation

  • Unified capture interface error
  • Pop-up prompts
  • Error redirection reported
  • Basic authentication
  • Form serialization

Implemented functions

  • Unified catch interface error: use axiOS built-in interceptor
  • Popup prompt: ImportElement UItheMessagecomponent
  • Error redirection: Route hook
  • Basic authentication: server-side expiration stamps and tokens, as well as routing-enabled hooks
  • Form serialization: I use it directlyqs(NPM module), you can write it yourself if you have time

rendering

The pit has been climbed, it is a bit troublesome to reproduce those mistakes now.. So you can’t record a motion picture

Usage and packaging

usage

// Service layer, the default import will find the directory of the index.js file, which may not be known by some friends
// You can learn about the introduction of NPM and the theoretical concepts introduced in ES6
import axiosPlugin from "./server"; 
Vue.use(axiosPlugin);

Copy the code
  • Wrapping axios (AXIos:index.js)
import axios from "axios";
import qs from "qs";
import { Message } from "element-ui";
import router from ".. /router";

const Axios = axios.create({
  baseURL: "/".// Because I do a reverse proxy locally
  timeout: 10000.responseType: "json".withCredentials: true.// Whether cookies are allowed
  headers: {
    "Content-Type": "application/x-www-form-urlencoded; charset=utf-8"}});// Serialize the POST pass (add request interceptor)
Axios.interceptors.request.use(
  config= > {
    // Do something before sending a request
    if (
      config.method === "post"
    ) {
      / / the serialization
      config.data = qs.stringify(config.data);
      // Warm reminder, if your company's submission can directly accept json format, you can not use QS to serialize
    }

    // If there is an authentication token, put the token on the header
    // If you need to store cookies across sites, it is better to store cookies. Some browsing environments limit the use of localStorage
    // localStorage is usually written locally after the request is successful, because you put it in vuex refresh will not be
    // Some necessary data is written locally, preferentially read from locally
    if (localStorage.token) {
      config.headers.Authorization = localStorage.token;
    }
    return config;
  },
  error => {
    // Error callback information, see your definition
    Message({
      // Ele. me message popup module, similar to toast
      showClose: true.message: error && error.data.error.message,
      type: 'error'
    });
    return Promise.reject(error.data.error.message); });// Return status judgment (add response interceptor)
Axios.interceptors.response.use(
  res= > {
    // Do something with the response data
    if(res.data && ! res.data.success) { Message({// Ele. me message popup module, similar to toast
        showClose: true.message: res.data.error.message.message
          ? res.data.error.message.message
          : res.data.error.message,
        type: "error"
      });
      return Promise.reject(res.data.error.message);
    }
    return res;
  },
  error => {
    // The user is given basic information when logging in, such as username,token, expiration timestamp
    // Drop localStorage or sessionStorage directly
    if (!window.localStorage.getItem("loginUserBaseInfo")) {
      // If no authentication information is found during the interface access, return to the login page
      router.push({
        path: "/login"
      });
    } else {
      // If there is basic information, determine the timestamp and the current time, if the current time is greater than the server expiration time
      // Go back to the login page and log in again
      let lifeTime =
        JSON.parse(window.localStorage.getItem("loginUserBaseInfo")).lifeTime *
        1000;
      let nowTime = new Date().getTime(); // Timestamp of the current time
      console.log(nowTime, lifeTime);
      console.log(nowTime > lifeTime);
      if (nowTime > lifeTime) {
        Message({
          showClose: true.message: "Login status information expired, please log in again.".type: "error"
        });
        router.push({
          path: "/login"
        });
      } else {
        // The following is the satus of the interface callback, because I made some error pages, so they all point to the corresponding error page
        if (error.response.status === 403) {
          router.push({
            path: "/error/403"
          });
        }
        if (error.response.status === 500) {
          router.push({
            path: "/error/500"
          });
        }
        if (error.response.status === 502) {
          router.push({
            path: "/error/502"
          });
        }
        if (error.response.status === 404) {
          router.push({
            path: "/error/404"}); }}}// Return an error message in response
    let errorInfo =  error.data.error ? error.data.error.message : error.data;
    return Promise.reject(errorInfo); });// Repackage the instance of Axios as a plugin for vue.use (XXXX)
export default {
  install: function(Vue, Option) {
    Object.defineProperty(Vue.prototype, "$http", { value: Axios }); }};Copy the code

Router: Router:index.js)


import Vue from "vue";
import Router from "vue-router";
import layout from "@/components/layout/layout";
// There are too many modules for independent routing management, which is lazy loading import
import customerManage from "./customerManage"; // Customer management
import account from "./account"; / / login
import adManage from "./adManage"; // Advertising management
import dataStat from "./dataStat"; // Data statistics
import logger from "./logger"; / / log
import manager from "./manager"; / / manager
import putonManage from "./putonManage"; // Drop management
import error from "./error"; // Server error
import { Message } from "element-ui";

Vue.use(Router);

// Please skip this paragraph and look at the following
const router = new Router({
  hashbang: false.mode: "history".routes: [{path: "/".redirect: "/adver".component: layout,
      children: [ ...customerManage, ...adManage, ...dataStat, ...putonManage, ...manager, ...logger ] }, ... account, ... error ] });// Route interception
// I forgot to mention that not all sections require authentication
// If authentication is required, I will add a field requireLogin to the route meta and set it to true
// This product must be authenticated, such as the login page do not need, can be accessed directly!!
router.beforeEach((to, from, next) = > {
  if (to.matched.some(res= > res.meta.requireLogin)) {
    // Determine whether the login permission is required
    if (window.localStorage.getItem("loginUserBaseInfo")) {
      // Determine whether to log in
      let lifeTime =
        JSON.parse(window.localStorage.getItem("loginUserBaseInfo")).lifeTime *
        1000;
      let nowTime = (new Date()).getTime(); // Timestamp of the current time
      if (nowTime < lifeTime) {
        next();
      } else {
        Message({
          showClose: true.message: "Login status information expired, please log in again.".type: "error"
        });
        next({
          path: "/login"}); }}else {
      // If no login is displayed, the login page is displayed
      next({
        path: "/login"}); }}else{ next(); }});export default router;

Copy the code

Axios can be configured with a number of options. See the official website for more details


export default {
  // Request an address
  url: "/user".// Request type
  method: "get".// Please root path
  baseURL: "http://www.mt.com/api".// Data processing before request
  transformRequest: [function(data) {}].// Data processing after request
  transformResponse: [function(data) {}].// Custom request headers
  headers: { "x-Requested-With": "XMLHttpRequest" },
  // URL query object
  params: { id: 12 },
  // Query the object serialization function
  paramsSerializer: function(params) {},
  // request body
  data: { key: "aa" },
  // Set timeout to s
  timeout: 1000.// Whether to carry Token across domains
  withCredentials: false.// Customize request handling
  adapter: function(resolve, reject, config) {},
  // Authentication information
  auth: { uname: "".pwd: "12" },
  // Response data format json/blob /document/arrayBuffer/text/stream
  responseType: "json"./ / XSRF Settings
  xsrfCookieName: "XSRF-TOKEN".xsrfHeaderName: "X-XSRF-TOKEN".// Upload and download progress callback
  onUploadProgress: function(progressEvent) {
    Math.round(progressEvent.loaded * 100 / progressEvent.total);
  },
  onDownloadProgress: function(progressEvent) {},

  // Maximum number of forwards, for Node.js
  maxRedirects: 5.// Maximum response data size
  maxContentLength: 2000.// Customize the error status code range
  validateStatus: function(status) {
    return status >= 200 && status < 300;
  },
  / / for the node. Js
  httpAgent: new http.Agent({ keepAlive: true }),
  httpsAgent: new https.Agent({ keepAlive: true }),

  // Used to set up the cross-domain request broker
  proxy: {
    host: "127.0.0.1".port: 8080.auth: {
      username: "aa".password: "2123"}},// Used to cancel the request
  cancelToken: new CancelToken(function(cancel) {}};Copy the code

conclusion

My package is not a cure-all version, but I feel that most axios and Vue partners can be used directly with a little modification

Authentication needs to be more rigorous. For example, token can follow JWT specifications and introduce mid-layer NodeJS (interception, encapsulation, encryption and decryption of transmission, aggregation interface).