Vue+axios封裝請求實現前后端分離
本文實例為大家分享了Vue+axios封裝請求實現前后端分離的具體代碼,供大家參考,具體內容如下
前言
我們需要進行前后端分離開發(fā),那么前后端的跨域問題就是無可避免的問題,前后端的請求也是無可避免的,Vue之中有一個請求組件是axios,我們可以對axios進行封裝作為我們請求的工具組件
# 一、封裝axios
vue.config.js 配置文件
module.exports = {
configureWebpack: {
resolve: {
alias: {
api: '@/api',
assets: '@/assets',
components: '@/components',
layouts: '@/layouts',
router: '@/router',
store: '@/store',
utils: '@/utils',
views: '@/views'
}
}
},
devServer: {
//端口
port: 8081,
//后端接口
proxy: {
'/api': {
target: 'http://localhost:8099', // 目標代理接口地址
changeOrigin: true, // 開啟代理,在本地創(chuàng)建一個虛擬服務端
// ws: true, // 是否啟用websockets
pathRewrite: {
'^/api': ''
}
}
}
}
}
request.js,封裝組件
//配置axios
import axios from 'axios'
const instance = axios.create({
baseURL: '/api',
timeout: 6000
})
instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
//請求攔截器
instance.interceptors.request.use(
function(config) {
return config
},
function(error) {
//對請求錯誤做些什么
return Promise.reject(error)
}
)
//響應攔截器
instance.interceptors.response.use(
function(response) {
return response.data
},
function(error) {
//對響應錯誤做點什么
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('未知的method' + method)
return false
}
}
api.js,接口文件
import req from '@/utils/request'
/**
* 批量查詢
* @param params
*/
export const list = params => req("get", "/resource/list", params);
具體的頁面之中進行導入使用即可
總結
這就是vue中對于axios的初步封裝使用,后續(xù)會持續(xù)更新
關于vue.js組件的教程,請大家點擊專題vue.js組件學習教程進行學習。
更多vue學習教程請閱讀專題《vue實戰(zhàn)教程》
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
element-plus 在vue3 中不生效的原因解決方法(element-plus引入)
這篇文章主要介紹了element-plus 在vue3 中不生效的原因解決方法(element-plus引入),本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-08-08
Vue中使用Echarts響應式布局flexible.js+rem適配方案詳解
這篇文章主要介紹了Vue中使用Echarts響應式布局flexible.js+rem適配方案詳解,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-01-01
vuejs使用axios異步訪問時用get和post的實例講解
今天小編就為大家分享一篇vuejs使用axios異步訪問時用get和post的實例講解,具有很好的參考價值。希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08

