A complete tutorial on using axios encapsulation in vue

A complete tutorial on using axios encapsulation in vue

Preface

Nowadays, in projects, the Axios library is commonly used for Http interface requests. It is a promise-based http library that can run on the browser and in node.js. In addition, it has excellent features such as intercepting requests and responses, converting JSON data, and client-side defense against XSRF.

Considering that the writing methods are confusing and inconsistent when actually used in various projects. Axios is encapsulated in a generalized way to help simplify the code and facilitate later updates and maintenance, making it as general as possible.

Here’s how

1. Install axios in vue

	npm install axios -S
	Or npm i axios -S

2. Globally import in main.js

	import axios from 'axios'
	Vue.prototype.$axios = axios //Bind axios to the prototype of Vue

3. Configure cross-domain in vue.config.js in the root directory

	module.exports = {
	 publicPath: './',
	 //Configure cross-domain requests devServer: {
	  open: true, //Whether to automatically open the browser https: false, //Whether to enable https
	  hotOnly: false,
	  proxy: { // Configure cross-domain '/api': {
	    target: 'http://********', //Request interface domain name ws: true,
	    secure: false,
	    changOrigin: true, //Whether to allow crossing pathRewrite: {
	     '^/api': ''
	    }
	   }
	  },
	  before: app => { }
	 }
	}

4. Create an api.js file in the api folder under the src subdirectory to simply encapsulate axios

import axios from 'axios'
//Here we reference element's loading full screen loading import { Loading } from "element-ui";

const service = axios.create({
 baseURL: '/',
 timeout: 30000 // Set request timeout})
let loading = "";
// Request interceptor service.interceptors.request.use(
 (config) => {
  // Do some processing before the request is sent if (!(config.headers['Content-Type'])) {
   loading = Loading.service({
    lock: true,
    text: "Loading...",
    spinner: "el-icon-loading",
    background: "rgba(255,255,255,0.7)",
    customClass: "request-loading",
   });
   if (config.method == 'post') {
    config.headers['Content-Type'] =
     'application/json;charset=UTF-8'
    for (var key in config.data) {
     if (config.data[key] === '') {
      delete config.data[key]
     }
    }
    config.data = JSON.stringify(config.data)
   } else {
    config.headers['Content-Type'] =
     'application/x-www-form-urlencoded;charset=UTF-8'
    config.data = JSON.stringify(config.data)
   }
  }
  const token = "token"
  // Let each request carry a token-- ['X-Token'] is a custom key. Please modify it according to the actual situation. if (token) {
   config.headers['Authorization'] = token
  }
  return config
 },
 (error) => {
  loading.close();
  // Sending failed console.log(error)
  return Promise.reject(error)
 }
)

// Response interceptor service.interceptors.response.use(
 (response) => {

  loading.close();
  // dataAxios is the data returned by axios
  // loadingInstance.close();
  const dataAxios = response.data
  // This status code is the return dataAxios agreed with the backend
 },
 (error) => {
  return Promise.reject(error)
 }
)

	export default service

5. Create an http file in the api folder

 // Import the packaged axios
 // ps: If there is no encapsulation, you can import axios from "./api";
	// /api is the path variable for configuring cross-domain let reportUpload= '/api/report/upload'
  export const Upload= () => {
   return axios.get( reportUpload )
  }

6. Call the interface in the page

//Introduce the encapsulated interface import { Upload} from "@/api/http.js"; 

// Call using async Upload() {
  let { result } = await getlist ();
  	console.log(result)
 },

Summarize

This is the end of this article about the use of axios encapsulation in vue. For more relevant vue axios encapsulation content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • How to use Vue-axios for data interaction
  • Vue project practice elegant use of axios
  • How to use axios request in Vue project
  • Vue global use of axios operation
  • Detailed explanation of the use of axios in vue

<<:  MySQL 5.7 installation MySQL service cannot be started but the service does not report any errors

>>:  Solution to MySQLSyntaxErrorException when connecting to MySQL using bitronix

Recommend

Thumbnail hover effect implemented with CSS3

Achieve resultsImplementation Code html <heade...

Detailed explanation of replace into example in mysql

Detailed explanation of replace into example in m...

Mysql timeline data to obtain the first three data of the same day

Create table data CREATE TABLE `praise_info` ( `i...

How to use HTML form with multiple examples

Nine simple examples analyze the use of HTML form...

Detailed explanation of VUE Token's invalidation process

Table of contents Target Thought Analysis Code la...

CSS code for arranging photos in Moments

First, you can open Moments and observe several l...

jQuery achieves large-screen scrolling playback effect

This article shares the specific code of jQuery t...

How to solve the 2002 error when installing MySQL database on Alibaba Cloud

The following error occurred while installing the...

What do CN2, GIA, CIA, BGP and IPLC mean?

What is CN2 line? CN2 stands for China Telecom Ne...

MySQL 5.7.15 version installation and configuration method graphic tutorial

This article shares with you a detailed tutorial ...

How to install and configure MySQL and change the root password

1. Installation apt-get install mysql-server requ...

Detailed explanation of storage engine in MySQL

MySQL storage engine overview What is a storage e...