API Call instance

. methed: { ... // API async to query users by accountgetUser() {
    const {account} = this
    const data = {
      account 
    }
    await this.$api.getUsers({data, // successful callback onSuccess: res => {//? To select chained calls, if data is null, no error will be reported, undefined will be returned, need polifyletlist = res ? .data ? The pageData | | [] / / processing data list. ForEach ((item, index) = > {item. Children & & delete item. The children; item.key = index }); this.list = list; }})},mounted() {
    this.loading = true
    await this.getUser()

    await this.anotherApi
    await this.anotherApi
    await this.anotherApi

    this.loading = false}... }Copy the code

Before the request, you can open the loading switch and call the interface requesting function with await. After the request is completed, you can continue to run the program and close the loading switch

Fetch. Js encapsulates the process

  • axios

  import axios from 'axios'
Copy the code

Axios Chinese document

Axios is an HTTP client based on Promise for browsers and NodeJS, which itself has the following features:

  • Create an XMLHttpRequest from the browser
  • Make HTTP requests from nodeJS
  • Supporting Promise API
  • Intercept requests and responses
  • Transform request and response data
  • Cancel the request
  • Automatically convert JSON data
  • The client supports CSRF/XSRF prevention

Axios has very high support for VUE, and many VUE projects use AXIos as an API request plug-in. There are also many articles about secondary encapsulation of AXIos on the Internet, and the author also referred to the total multiple encapsulation method, and finally modified and designed this set of templates for his own use. The specific method of AXIOS is not detailed here, but if you are not very familiar with Axios, you can directly visit the document to learn.

In addition to AXIos, there are other API request schemes such as FETCH, and depending on the request scheme, the fetch. Js file can also be modified to meet the requirements.

  • message

import {
  notification
} from 'ant-design-vue'.function message(msg) {
  notification.error({
    message: "Server request exception",
    description: Tip: "" + msg
  })
}
Copy the code

The Message module is used to throw interface prompts. For example, an interface that modifies data returns a successful code. You can use message to pop up a message indicating that the change was successful. The same is true for a request failure. You can throw out the reason for the failure, etc. You can modify the corresponding components according to the project. For example, Element’s messageBox.

  • defaultSetting

Const defaultSetting = {// request method:'GET', // timeout duration ms timeout: 600000, // res.code Indicates the successful range statusMinStatusMax: 99999, // onGlobalFail:function(res) {message (res) message | | res., MSG)}, / / success computeSuccess condition calculation method:function (res) {
    if (res.status > 299) return false
    return 1 === res.data.code
  }
}
Copy the code

DefaultSetting Specifies the default parameters

  • Method Request method (GET, PSOT…)

  • Timeout Indicates the request timeout period ms

  • StatusMin, statusMax Range in which the status code returned by the request is judged successful. For example, min is set to 200 and Max is set to 399. (This status code is configured to judge the success of aixOS plug-in, because the author wrote the branch of success and failure, so here set 0 to 99999 as success, that is, return the result in all cases. A custom method to determine whether the request was successful

  • OnGlobalFail [Function] Global failure callback. This method can take an RES parameter, the request result. Executed when the custom method determines that the request failed. This method defaults to a global method and is applied to all requests. This method defaults to using the message method defined earlier, with a failure message displayed. This method can be overridden when a specific interface is called.

  • ComputeSuccess This method is used to calculate the success status, accepting the RES parameter, the result of the request. This method returns a Boolean, true if the request success logic is executed, false if the request failure logic is executed.

  • config


exportDefault async ({// request address url ="", // 'data' is the data that is sent as the body of the request // Without setting 'transformRequest', it must be one of the following types: // -string, plain Object, ArrayBuffer, ArrayBufferView, URLSearchParams  Stream data = {}, //"GET" "POST". Method = defaultsetting. method, // 'timeout' specifies the number of milliseconds for the request to timeout (0 indicates no timeout) // If the request takes longer than 'timeout', Timeout = defaultsetting. timeout, // 'withCredentials' indicates whether credentials withCredentials = are needed when making cross-domain requestsfalseMaxContentLength = 10000, // 'responseType' indicates the data type of the server response'arraybuffer'.'blob'.'document'.'json'.'text'.'stream'
  responseType = "json",
  validateStatus = (status) => {
    return status >= defaultSetting.statusMin&& status < defaultSetting.statusMax; // Default}, // 'onUploadProgress' allows the upload progress event onUploadProgress = () => {}, // 'onDownloadProgress' allows processing of progress events for downloads onDownloadProgress = () => {}, // 'cancelToken' specifies the cancel token used to cancel the request. // (see the Cancellation section below for more information.) // 'params' is the URL parameter to be sent with the request // Must be a plain object or URLSearchParams object params, //' auth 'means HTTP basic authentication should be used, And provide credentials // This sets an Authorization header, Override any existing Authorization headers set using headers, baseUrl, // headers = {}, // callback onSuccess =function(res) {}, // Failed callback onFail =function(res) {}, // Global callback (executed regardless of success or failure) onFinally =function(res) {}, // Global successful callback onGlobalSuccess =function(res) {}, / / global failure callback onGlobalFail = defaultSetting onGlobalFail, / / success conditions calculation method computeSuccess = defaultSetting.com puteSuccess}) = > {... }Copy the code

Here is the parameter config of the fetch method exported from fetch. Some of these parameters are used in the AXIOS request. Some parameters are used for successful and failed logic execution after the request.

  • request

 let_baseUrl = baseUrl | | defaultBaseUrl / / if you have redirectUrl, covering the url url = _baseUrl + url; // The parameters of the GET request are used in data, as in the POST requestif (method == "GET") {
    let dataStr = ""; // Use the data argument? & splicing dataStr = object.entries (data).reduce((dataStr, value) => {dataStr = dataStr + '${value[0]}=${value[1]}& `return dataStr
    }, dataStr)
    if(dataStr ! = ="") {
      dataStr = dataStr.substr(0, dataStr.lastIndexOf("&"));
      url = url + "?"+ dataStr; }}Copy the code

Concatenate url here

// config
letrequestConfig = { url, method: The default is get headers, params, data, timeout, withCredentials, auth, responseType, // The default is onUploadProgress, onDownloadProgress, maxContentLength, cancelToken, validateStatus }Copy the code

Config for AIxOS requests

Then (res => {const isSuccess = computeSuccess(res) const result = Res. data // The default success code is 1, which can be changed in the backgroundif (isSuccess) {
    onGlobalSuccess(result)
    onSuccess(result)
  } else {
    onGlobalFail(result)
    onFail(result)
  }
  onFinally(res)
})
Copy the code

Send the request, calculate the success status code through computeSuccess, and run the corresponding branch logic

  • Complete the fetch. Js

import axios from 'axios'

import {
  notification
} from 'ant-design-vue'

const defaultBaseUrl = "http://192.168.0.1"; Const defaultSetting = {// request method:'GET', // timeout duration ms timeout: 600000, // res.code Indicates the successful range statusMin: 200, statusMax: 99999, // onGlobalFail:function(res) {message (res) message | | res., MSG)}, / / success computeSuccess condition calculation method:function (res) {
    if (res.status > 299) return false
    return1 === res.data.code}} // The server reported an error message, can modify this function according to the framework, MSG is thrown messagefunction message(msg) {
  notification.error({
    message: "Server request exception",
    description: Tip: "" + msg
  })
}
exportDefault async ({// request address url ="", // 'data' is the data that is sent as the body of the request // Without setting 'transformRequest', it must be one of the following types: // -string, plain Object, ArrayBuffer, ArrayBufferView, URLSearchParams  Stream data = {}, //"GET" "POST". Method = defaultsetting. method, // 'timeout' specifies the number of milliseconds for the request to timeout (0 indicates no timeout) // If the request takes longer than 'timeout', Timeout = defaultsetting. timeout, // 'withCredentials' indicates whether credentials withCredentials = are needed when making cross-domain requestsfalseMaxContentLength = 10000, // 'responseType' indicates the data type of the server response'arraybuffer'.'blob'.'document'.'json'.'text'.'stream'
  responseType = "json",
  validateStatus = (status) => {
    return status >= defaultSetting.statusMin&& status < defaultSetting.statusMax; // Default}, // 'onUploadProgress' allows the upload progress event onUploadProgress = () => {}, // 'onDownloadProgress' allows processing of progress events for downloads onDownloadProgress = () => {}, // 'cancelToken' specifies the cancel token used to cancel the request. // (see the Cancellation section below for more information.) // 'params' is the URL parameter to be sent with the request // Must be a plain object or URLSearchParams object params, //' auth 'means HTTP basic authentication should be used, And provide credentials // This sets an Authorization header, Override any existing Authorization headers set using headers, baseUrl, // headers = {}, // callback onSuccess =function(res) {}, // Failed callback onFail =function(res) {}, // Global callback (executed regardless of success or failure) onFinally =function(res) {}, // Global successful callback onGlobalSuccess =function(res) {}, / / global failure callback onGlobalFail = defaultSetting onGlobalFail, / / success condition calculation method computeSuccess = defaultSetting.com puteSuccess = > {})let_baseUrl = baseUrl | | defaultBaseUrl / / if you have redirectUrl, covering the url url = _baseUrl + url; // The parameters of the GET request are used in data, as in the POST requestif (method == "GET") {
    let dataStr = ""; // Use the data argument? & splicing dataStr = object.entries (data).reduce((dataStr, value) => {dataStr = dataStr + '${value[0]}=${value[1]}& `return dataStr
    }, dataStr)
    if(dataStr ! = ="") {
      dataStr = dataStr.substr(0, dataStr.lastIndexOf("&"));
      url = url + "?" + dataStr;
    }
  }
  // config
  letrequestConfig = { url, method: The default is get headers, params, data, timeout, withCredentials, auth, responseType, // The default is onUploadProgress, onDownloadProgress, maxContentLength, cancelToken, Const isSuccess = computeSuccess(res) const isSuccess = computeSuccess(res) Const result = res.data // The success code defaults to 1, depending on backgroundif (isSuccess) {
      onGlobalSuccess(result)
      onSuccess(result)
    } else {
      onGlobalFail(result)
      onFail(result)
    }
    onFinally(res)
  })
};
Copy the code

api.js

import fetch from "./fetch.js";

exportconst api = { // 1. /login loginV2: config => fetch({ ... config, url:"/app/user/loginV2",
      onGlobalFail: function (res) {
        Modal.error({
          title: 'Login failed',
          content: res.message || res.msg
        })
      },
      method: "POST"GetUser: config => fetch({... config, url:"/app/user/findUser",
      method: "POST"}),... };Copy the code

With the introduction of fetch. Js, all interfaces are added to API objects exported. It is also possible to intercept individual interfaces individually. For example, all interfaces corresponding to getUser methods do not require pop-ups, so you can modify getUser here

. getUser: config => fetch({ ... config, onGlobalFail: () => {}, url:"/app/user/findUser",
      method: "POST"}),...Copy the code

This way, if the interface is called on multiple pages, there is no need to change it one by one.

main.js

. import { api } from'./api/api'

Vue.prototype.$api= api; .Copy the code

Mount the API to the Vue prototype

Now that we’re done, we can call the interface through this.$API.

mock

In development, we often need some virtual data. So, we can write a mock.js for mock data.

mock.js

export const loginData = {
  "code": 1,
  "msg": "success"."data": {
    "userId": 1,
    "account": "2222222222"."role": 3."password": null,
    "phone": "21121211221"."email": null,
    "unionId": null,
    "reName": null,
    "nickName": "xxx2"."accId": "dee2d504239649b6be54c1279926a4a7"."ytxAccount": "852b83a42d424f36bb9ef7d383acc08d"."headPic": "http://k1VoaL3.wlekjwqejklwq"."gender": 0."age": null,
    "birthday": null,
    "constellation": null,
    "bloodType": null,
    "profession": null,
    "address": null,
    "contact": null,
    "studyCfNum": null,
    "teacherCfNum": null,
    "state": 0."createTime": "The 2016-12-27 13:20:43"."lastUpdateTime": "The 2019-12-12 09:01:59"."lastLoginTime": "The 2020-01-02 17:50:14"."balance": null,
    "orgno": "00000768"."schoolName": null,
    "isBind": null,
    "onlineState": null,
    "userDevices": []."classList": []."clazzList": []."children": []."usrChildren": []."fileStore": null,
    "popenId": "oFwyg4vN-Wv9LMwNKafeeeeeWexM"."topenId": "ohH6X5JSLwHzwYNewqewqecagVeaw"}}Copy the code

mockedApi

import fetch from "./fetch.js";
import {
  loginData
} from './mock.js'
export const api = {
  // 1. /login
  loginV2: config => config.onSuccess(loginData),
};
Copy the code

Change the API import path in main.js to mockedapi.js. This way, when the backend interface is developed, it is very convenient to change the mock data to the official interface by changing the path back to the official interface.

The author just entered the line less than three months, trying to sum up some experience, output text. We asked them to correct it.