Vue+axios encapsulation request realizes front end separation
- 2021-08-31 07:20:00
- OfStack
This article example for everyone to share the Vue + axios encapsulation request to achieve front and back end separation of the specific code, for your reference, the specific content is as follows
Preface
We need to separate the front and back end development, so the cross-domain problem of the front and back end is inevitable, and the request of the front and back end is also inevitable. One of the request components in Vue is axios, and we can encapsulate axios as the tool component we request
# 1. Encapsulate axios
vue. config. js configuration file
module.exports = {
configureWebpack: {
resolve: {
alias: {
api: '@/api',
assets: '@/assets',
components: '@/components',
layouts: '@/layouts',
router: '@/router',
store: '@/store',
utils: '@/utils',
views: '@/views'
}
}
},
devServer: {
// Port
port: 8081,
// Backend interface
proxy: {
'/api': {
target: 'http://localhost:8099', // Destination Proxy Interface Address
changeOrigin: true, // Open the agent and create it locally 1 Virtual servers
// ws: true, // Enable or not websockets
pathRewrite: {
'^/api': ''
}
}
}
}
}
request. js, encapsulated component
// Configure axios
import axios from 'axios'
const instance = axios.create({
baseURL: '/api',
timeout: 6000
})
instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
// Request interceptor
instance.interceptors.request.use(
function(config) {
return config
},
function(error) {
// Do something about request errors
return Promise.reject(error)
}
)
// Response interceptor
instance.interceptors.response.use(
function(response) {
return response.data
},
function(error) {
// Do something about response errors
return Promise.reject(error)
}
)
export default function(method, url, data = '', config = '') {
method = method.toLowerCase()
if (method === 'post') {
if (config !== '') {
return instance.post(url, data, config)
} else {
return instance.post(url, data)
}
} else if (method === 'get') {
return instance.get(url, {params: data})
} else if (method === 'delete') {
return instance.delete(url, {params: data})
} else if (method === 'put') {
return instance.put(url, data)
} else {
console.error(' Unknown method' + method)
return false
}
}
api. js, interface file
import req from '@/utils/request'
/**
* Batch query
* @param params
*/
export const list = params => req("get", "/resource/list", params);
You can import and use it in specific pages
Summarize
This is the initial encapsulation use of axios in vue, which will be continuously updated in the future
For the vue. js component tutorial, please click on the topic vue. js component learning tutorial to learn.
For more vue learning tutorials, please read the special topic "vue Practical Tutorial"