Complete tutorial on the use of axios encapsulation in vue
- 2021-10-27 06:33:35
- OfStack
Preface
Nowadays, Axios library is widely used in projects to request Http interface. It is an http library based on promise, which can run on the browser side and node. js. In addition, there are excellent features such as intercepting requests and responses, transforming JSON data, and defending clients against XSRF.
Considering the actual use of each project writing confusion, not unified 1. Axios for 1 under the general encapsulation, the purpose is to help simplify the code and facilitate the later update maintenance, as far as possible general.
The method is as follows
1. vue Install axios
npm install axios -S
Or
npm i axios -S
2. Global import at main. js
import axios from 'axios'
Vue.prototype.$axios = axios // Will axios Bind to vue On the prototype of
3. Configure cross-domain in root vue. config. js
module.exports = {
publicPath: './',
// Configure cross-domain requests
devServer: {
open: true, // Do you want to open the browser automatically
https: false, // Whether to turn it on 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 api. js file under api folder under src subdirectory for simple encapsulation of axios
import axios from 'axios'
// It quotes here element Adj. loading Full screen loading
import { Loading } from "element-ui";
const service = axios.create({
baseURL: '/',
timeout: 30000 // Set the request timeout
})
let loading = "";
// Request interceptor
service.interceptors.request.use(
(config) => {
// Do it before the request is sent 1 Some treatment
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 token-- ['X-Token'] For custom key Please modify it according to the actual situation
if (token) {
config.headers['Authorization'] = token
}
return config
},
(error) => {
loading.close();
// Send failed
console.log(error)
return Promise.reject(error)
}
)
// Response interceptor
service.interceptors.response.use(
(response) => {
loading.close();
// dataAxios Yes axios Returns the data
// loadingInstance.close();
const dataAxios = response.data
// This status code is agreed with the back end
return dataAxios
},
(error) => {
return Promise.reject(error)
}
)
export default service
5. Create an http file under the api folder
// Introduce packaged axios
// ps: If there is no encapsulation, import it normally axios You can
import axios from "./api";
// /api To configure cross-domain path variables
let reportUpload= '/api/report/upload'
export const Upload= () => {
return axios.get( reportUpload )
}
6. Call the interface in the page
// Introducing encapsulated interfaces
import { Upload} from "@/api/http.js";
// Use when calling
async Upload() {
let { result } = await getlist ();
console.log(result)
},