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

MySQL insert json problem

MySQL 5.7.8 and later began to support a native J...

Web interview Vue custom components and calling methods

Import: Due to project requirements, we will enca...

Example of how to quickly build a Redis cluster with Docker

What is Redis Cluster Redis cluster is a distribu...

Vue implements dynamic query rule generation component

1. Dynamic query rules The dynamic query rules ar...

Getting Started Guide to MySQL Sharding

Preface Relational databases are more likely to b...

How to understand semantic HTML structure

I believe everyone knows HTML and CSS, knows the ...

About the pitfall record of Vue3 transition animation

Table of contents background Problem location Fur...

Implement MySQL read-write separation and load balancing based on OneProxy

Introduction Part 1: Written at the beginning One...

Summary of knowledge points about covering index in MySQL

If an index contains (or covers) the values ​​of ...

docker logs - view the implementation of docker container logs

You can view the container logs through the docke...

Detailed explanation of destructuring assignment syntax in Javascript

Preface The "destructuring assignment syntax...

Summary of Linux vi command knowledge points and usage

Detailed explanation of Linux vi command The vi e...

jQuery canvas draws picture verification code example

This article example shares the specific code of ...

Example code for using @media in CSS3 to achieve web page adaptation

Nowadays, the screen resolution of computer monit...

Issues and precautions about setting maxPostSize for Tomcat

1. Why set maxPostSize? The tomcat container has ...