SoFunction
Updated on 2025-04-07

Detailed explanation of the packaging and use of axios by Vue front-end

Axios is a promise-based HTTP library. After packaging axios, it can be developed more efficiently and facilitated to maintain, and can also be applied directly in future projects, so it is necessary to package it well. After referring to many methods, I pieced together a set of methods that I think are very practical.

First, there are two files in the http directory

This is a functional file including splicing urls, filtering parameters, etc., which collects methods into a file for easy maintenance and modification.
Just read it and know what functions it has

const helper = {
 // Get the parameter value of the address bar according to name getQueryString (name) {
  let reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`)
  let hash = 
  let search = ('?')
  let r = search[1] && search[1].match(reg)
  if (r != null) return r[2]; return ''
 },
 // Splice parameters to url queryString (url, query) {
  let str = []
  for (let key in query) {
   (key + '=' + query[key])
  }
  let paramStr = ('&')
  return paramStr ? `${url}?${paramStr}` : url
 },
 
// Custom judge element type JS toType(obj) {
	 return ({}).(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
	},
// Parameter filtering function filterNull(o) {
	 for (var key in o) {
	  if (o[key] === null) {
	   delete o[key]
	  }
	  if (toType(o[key]) === 'string') {
	   o[key] = o[key].trim()
	  } else if (toType(o[key]) === 'object') {
	   o[key] = filterNull(o[key])
	  } else if (toType(o[key]) === 'array') {
	   o[key] = filterNull(o[key])
	  } else if (toType(o[key]) === 'number') {
	   o[key] = filterNull(o[key])
	  }
	 }
	 return o
	}

}
export default helper

Receive requests, expose the interface, including parameter params, URLs and tokens sent to the backend (if students who do not use JWT, they can omit parameter tokens), and send them to the backend after processing.

import axios from 'axios'
let qs = require('querystring')
import helper from './helper'

//( .NODE_ENV)
//Judge the environment to provide a baseURL, and be sure to be consistent with the background addresslet root = .NODE_ENV === 'development'
 // Development environment API interface ?
 `http://localhost:3001/api`
 // Production environment API interface :
 `http://127.0.0.1:3001/api`;
// Reference axios and set header file['Content-Type'] = 'application/x-www-form-urlencoded';


function apiAxios(method, url, params, token) {
 if (params) {
  params = (params)
 }
 return axios({
  method: method,
  //Splicing parameters  url: method === 'GET'|| method === 'DELETE' ? (url,params) : url,
  data: method === 'POST' || method === 'PUT' ? (params) : null,
  baseURL: root,
  timeout: 10000,
  headers: { Authorization: `Bearer ${token}` },	//jwt
  withCredentials: false
 })
}

// Return the calling interface in the vue templateexport default {
 get: function (url, params, token) {
  return apiAxios('GET', url, params, token)
 },
 post: function (url, params, token) {
  return apiAxios('POST', url, params, token)
 },
 put: function (url, params, token) {
  return apiAxios('PUT', url, params, token)
 },
 delete: function (url, params, token) {
  return apiAxios('DELETE', url, params, token)
 },
}

Encapsulate the front-end API interface and accept requests from the front-end page. After encapsulation, you can judge the type and url to the axios file based on the function name, which is convenient for maintenance and development.

import http from '../http/'
export default {
 login(data, token){
  return ("/login",data, token)
 },
 getUserInfo(data, token){
  return ("/getUserInfo",data, token)
 }
}

After reference, you can call it globally

In the front-end, you can use this.$() format to send requests, or you can use this.$http directly without going through the API, but you have to write url every time, which is more troublesome when there are many interfaces. Therefore, it is recommended to use API to encapsulate it.

import api from './api/'
import http from './http/'
//Define global variables.$api = api

.$http = http

Used in the front end:

Since axios returns a promise object, it is necessary to receive the response sent back by the backend in the form of .then, and then provide corresponding feedback.

//Turn directly use this.$api to call the API interface. If the API interface is not encapsulated, you can use this.$http this.$(data, token).then((res) => {
	(res)
 }).catch((err) => {
 	(res)
 })

The above is the detailed explanation and integration of the packaging and use of Vue front-end that the editor introduced to you. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!