In the vue project, we can get the backend data using axios. There are many places to use it. I always like to write the code neat and neat. Therefore, the axios request is encapsulated, convenient to use, and a lot of redundant code is reduced.
The catalogue is as follows:
|-------src
| |-- api
| | |-- http.js
| | |-- roleApi.js
| |-- views
| | |-- role.vue
(1) Firstly, encapsulate axios get, post method, request interception (request pre-processing request) and response interceptor (data after processing request response). New file http.js:
import axios from 'axios' import { Message } from 'element-ui' // create an axios instance const http = axios.create({ baseURL: 'Backend interface address', // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url // withCredentials: true, // send cookies when cross-domain requests timeout: 50000 // request timeout }) // Set post, put default Content-Type http.defaults.headers.post['Content-Type'] = 'application/json' http.defaults.headers.put['Content-Type'] = 'application/json' // request interceptor request interception (request pre-processing request) http.interceptors.request.use( config => { // do something before request is sent return config }, error => { // do something with request error console.log(error) // for debug return Promise.reject(error) } ) // Response interceptor response interceptor (processing response data) http.interceptors.response.use( /** * If you want to get http information such as headers or status * Please return response => response */ /** * Determine the request status by custom code * Here is just an example * You can also judge the status by HTTP Status Code */ response => { const res = response.data const ressuc = res.success // The success or failure of the back end return is judged by success true and false, so the success of response.data is obtained here. if (ressuc) { console.log('response', response) return res } else { Message({ message: res.message || 'error', type: 'error', duration: 5 * 1000 }) } }, error => { console.log('err' + error) // for debug Message({ message: error.message, type: 'error', duration: 5 * 1000 }) return Promise.reject(error) } ) // Encapsulation get method export function get({ url, params }) { return new Promise((resolve, reject) => { http.get(url, { params: params }).then(res => { resolve(res.data) }).catch(err => { reject(err.data) }) }) } // Encapsulating post method export function post({ url, params }) { return new Promise((resolve, reject) => { http.post(url, params).then(res => { resolve(res.data) }).catch(err => { reject(err.data) }) }) }
(2) Next, encapsulate different requests and create a new file roleApi.js:
import { get, post } from './http' // Importing methods in axios instance files const server = { //get method with parameters getById(param) { return get({ url: '/role/getById', method: 'get', params: param }) } //get method without parameters getAll() { return get({ url: '/role/getAll', method: 'get' }) }, // post method save(param) { return post({ url: '/role/save', method: 'post', params: param }) } } export default server
(3) Finally, the api file is imported directly into the business module and used in the role.vue file:
import apis from '@/api/roleApi' // Wrap it with try catch and execute the code in catch when the request fails try { const param = { id: 'admin' } const res = await apis.getById(param) console.log('getById:', res) } catch (e) { //Prompt error console.log(e) }
In this way, it is very convenient to use axios with only one simple code to get the return result.~