Installing Axios
npm install axios --save
Create an instance (Utils/fetch.js)
Axios default submission format is:application/json
You can use the QS module (required to install) to convert the submitted format toapplication/x-www-form-urlencoded
data => qs.stringify(data)
you can submit a normal form by setting the Transformrequest property
import axios from 'axios'const instance = axios.create({ baseURL: 'apiBaseUrl', // api的base_url timeout: 10000 // 请求超时时间 // transformRequest: data => qs.stringify(data) //})// request拦截器instance.interceptors.request.use( e => { e.params = e.params || {} e.headers = e.headers || {} //set 默认值 return e }, error => ({ status: 0, msg: error.message }))// respone拦截器instance.interceptors.response.use( response => { const resp = response.data if (response.status === 200) { return resp } return resp }, error => { console.log('err' + error) // for debug return Promise.reject(error) })export default instance
Encapsulating API requests under the API folder
Create a new interface module in the API file and use the Axios instance (utils/fetch.js)
Src/api/api_test.js
import request from '@/utils/fetch'export function test(data) { return request({ url: '/test', method: 'post', data: data })}
When used, the api/module can be introduced by introducing the. js call method, or you can extend the API interface to the Vue instance by installing the plug-in, making it easier to use in the project
Create a $API extension with the test module as an example
Src/api/index.js
import * as api_test from './test'const apiObj = { api_test}const install = function(Vue) { if (install.installed) return install.installed = true Object.defineProperties(Vue.prototype, { $api: { get() { return apiObj } } })}export default { install}
Install $API extensions in Main.js:
import api from './api'Vue.use(api)
Called in the project:this.$api.api_test.test().then(resp=>{...}).catch(()=>{...})
Vue Project Practice-Add Axios Encapsulation API request