preface
In the last part, the overall architecture has been built and the HTTP request tool has been omitted. This part mainly aims to improve and supplement the use of AXIOS, the HTTP request tool.
portal
Build Vite2+Vue3 From zero (1)
Architecture design based on Vue
HTTP request tool
Here we use axios\textrm\color{red}{axios} Axios to make the HTTP request invocation
Install axios
npm install axios -s
Copy the code
Encapsulate the AXIos request by creating request.js
import axios from 'axios' import { ElLoading, ElMessage } from 'element-plus'; // Create an instance of axios const instance = axios.create({baseURL: import.meta.env.vite_app_URL, // timeout: Headers: {' content-type ': 'application/json; charset=UTF-8; ', } }) let loading; Loading const showLoading = () => {if (requestCount === 0 &&! Loading) {loading = elload.service ({text: "loading ", background: 'rgba(0, 0, 0, 0.7)', spinner: 'el-icon-loading', }) } requestCount++; Loading const hideLoading = () => {requestCount-- if (requestCount == 0) {load.close ()}} // instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; // instance.defaults.headers.get['Content-Type'] = 'application/x-www-form-urlencoded'; // instance.defaults.transformRequest = [function (data) { // let ret = '' // for (let it in data) { // ret += EncodeURIComponent (it) + '=' + encodeURIComponent(data[it]) + '&' //} // return ret //}] // Request interceptor Instance. The interceptors. Request. Use ((config) = > {showLoading () / / every time before sending a request to judge the existence of a token, if present, are unified in the HTTP request header will add token, Not every request manually add the const token = window. The localStorage. The getItem (" token "); Token && (config. Headers. Authorization = token) / / if the requests for the post, If (config.method === 'POST') {config.data = json.stringify (config.data); } return config; }, (error) => // Do something about the request error promise.reject (error)); / / response interceptor instance. Interceptors. Response. Use ((response) = > {hideLoading () / / response successful return response. The data; }, (error) => {console.log(error) // Error in response if (error.response && error-.response.status) {const status = Error.Response.status switch (status) {case 400: message = 'request error '; break; Case 401: message = 'request error '; break; Case 404: message = 'error requesting address '; break; Case 408: message = 'request timeout '; break; Case 500: message = 'Internal server error! '; break; Case 501: message = 'service not implemented! '; break; Case 502: message = 'Gateway error! '; break; Case 503: message = 'Service unavailable! '; break; Case 504: message = 'gateway timeout! '; break; Case 505: message = 'HTTP version not supported '; break; Default: message = 'request failed'} elmessage.error (message); return Promise.reject(error); } return Promise.reject(error); }); const axios = ({ method, url, data, config }) => { method = method.toLowerCase(); if (method == 'post') { return instance.post(url, data, { ... config }) } else if (method == 'get') { return instance.get(url, { params: data, ... config }) } else if (method == 'delete') { return instance.delete(url, { params: data, ... config }) } else if (method == 'put') { return instance.put(url, data, { ... Config})} else {console.error(' error: ${method} ') return false}} export default axiosCopy the code
Encapsulating API requests
Import request from '@/ API /user.js' export function login(data) {return request({url: '/ API /login', method: 'post', data, config: { headers: { 'Content-Type': 'application/x-www-form-urlencoded; Charset = utF-8 '}, timeout: 10000}})} export function getInfo(data) {return request({url: '/api/userinfo', method: 'get', params: data }) }Copy the code
Used by vue components
Function onLogin() {login({username: 'admin', PWD: 'admin'}).then(res => {// logic})}Copy the code