PrefaceNowadays, 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 how1. 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) }, SummarizeThis 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:
|
>>: Solution to MySQLSyntaxErrorException when connecting to MySQL using bitronix
question The tomcat container was successfully ad...
Achieve resultsImplementation Code html <heade...
Detailed explanation of replace into example in m...
Create table data CREATE TABLE `praise_info` ( `i...
Nine simple examples analyze the use of HTML form...
Table of contents Target Thought Analysis Code la...
First, you can open Moments and observe several l...
This article shares the specific code of jQuery t...
1. Python installation 1. Create a folder. mkdir ...
The following error occurred while installing the...
What is CN2 line? CN2 stands for China Telecom Ne...
Because we were going to build a website, in addi...
This article shares with you a detailed tutorial ...
1. Installation apt-get install mysql-server requ...
MySQL storage engine overview What is a storage e...