vue中axios封裝使用的完整教程
前言
如今,在項(xiàng)目中,普遍采用Axios庫(kù)進(jìn)行Http接口請(qǐng)求。它是基于promise的http庫(kù),可運(yùn)行在瀏覽器端和node.js中。此外還有攔截請(qǐng)求和響應(yīng)、轉(zhuǎn)換JSON數(shù)據(jù)、客戶端防御XSRF等優(yōu)秀的特性。
考慮到各個(gè)項(xiàng)目實(shí)際使用時(shí)寫法混亂,不統(tǒng)一。對(duì)Axios進(jìn)行一下通用化的封裝,目的是幫助簡(jiǎn)化代碼和利于后期的更新維護(hù),盡量通用化。
方法如下
1. vue安裝axios
npm install axios -S 或者 npm i axios -S
2. 在main.js進(jìn)行全局引入
import axios from 'axios' Vue.prototype.$axios = axios //將axios綁定到vue的原型上
3. 配置跨域 在根目錄下vue.config.js里邊
module.exports = {
publicPath: './',
//配置跨域請(qǐng)求
devServer: {
open: true, //是否自動(dòng)打開(kāi)瀏覽器
https: false, //是否開(kāi)啟https
hotOnly: false,
proxy: { // 配置跨域
'/api': {
target: 'http://********', //請(qǐng)求接口域名
ws: true,
secure: false,
changOrigin: true, //是否允許跨越
pathRewrite: {
'^/api': ''
}
}
},
before: app => { }
}
}
4. 在src子目錄下的api文件夾下創(chuàng)建api.js文件進(jìn)行簡(jiǎn)單的封裝axios
import axios from 'axios'
//這里引用了element的loading全屏加載
import { Loading } from "element-ui";
const service = axios.create({
baseURL: '/',
timeout: 30000 // 設(shè)置請(qǐng)求超時(shí)時(shí)間
})
let loading = "";
// 請(qǐng)求攔截器
service.interceptors.request.use(
(config) => {
// 在請(qǐng)求發(fā)送之前做一些處理
if (!(config.headers['Content-Type'])) {
loading = Loading.service({
lock: true,
text: "加載中...",
spinner: "el-icon-loading",
background: "rgba(255,255,255,0.7)",
customClass: "request-loading",
});
if (config.method == 'post') {
config.headers['Content-Type'] =
'application/json;charset=UTF-8'
for (var key in config.data) {
if (config.data[key] === '') {
delete config.data[key]
}
}
config.data = JSON.stringify(config.data)
} else {
config.headers['Content-Type'] =
'application/x-www-form-urlencoded;charset=UTF-8'
config.data = JSON.stringify(config.data)
}
}
const token = "token"
// 讓每個(gè)請(qǐng)求攜帶token-- ['X-Token']為自定義key 請(qǐng)根據(jù)實(shí)際情況自行修改
if (token) {
config.headers['Authorization'] = token
}
return config
},
(error) => {
loading.close();
// 發(fā)送失敗
console.log(error)
return Promise.reject(error)
}
)
// 響應(yīng)攔截器
service.interceptors.response.use(
(response) => {
loading.close();
// dataAxios 是 axios 返回?cái)?shù)據(jù)中的 data
// loadingInstance.close();
const dataAxios = response.data
// 這個(gè)狀態(tài)碼是和后端約定的
return dataAxios
},
(error) => {
return Promise.reject(error)
}
)
export default service
5. 在api文件夾下創(chuàng)建http文件
// 引入封裝好的axios
// ps:如果沒(méi)有封裝,正常引入axios即可
import axios from "./api";
// /api為配置跨域的路徑變量
let reportUpload= '/api/report/upload'
export const Upload= () => {
return axios.get( reportUpload )
}
6. 在頁(yè)面中調(diào)用接口
// 引入封裝好的接口
import { Upload} from "@/api/http.js";
// 調(diào)用時(shí)使用
async Upload() {
let { result } = await getlist ();
console.log(result)
},
總結(jié)
到此這篇關(guān)于vue中axios封裝使用的文章就介紹到這了,更多相關(guān)vue axios封裝使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vite打包優(yōu)化CDN壓縮的分析實(shí)現(xiàn)
我們?cè)谌粘5墓ぷ髦锌隙〞?huì)遇到項(xiàng)目打包優(yōu)化等問(wèn)題,本文主要介紹了vite打包優(yōu)化CDN壓縮的分析實(shí)現(xiàn),具有一定的參加價(jià)值,感興趣的可以了解一下2024-07-07
vue使用css-rcurlyexpected等less報(bào)錯(cuò)問(wèn)題
這篇文章主要介紹了vue使用css-rcurlyexpected等less報(bào)錯(cuò)問(wèn)題,具有很的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-10-10
基于ElementUI中Table嵌套實(shí)現(xiàn)多選的示例代碼
這篇文章主要介紹了基于ElementUI中Table嵌套實(shí)現(xiàn)多選的示例代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03
解決vux 中popup 組件Mask 遮罩在最上層的問(wèn)題
這篇文章主要介紹了解決vux 中popup 組件Mask 遮罩在最上層的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-11-11

