vue中axios封裝使用的完整教程
前言
如今,在項目中,普遍采用Axios庫進(jìn)行Http接口請求。它是基于promise的http庫,可運行在瀏覽器端和node.js中。此外還有攔截請求和響應(yīng)、轉(zhuǎn)換JSON數(shù)據(jù)、客戶端防御XSRF等優(yōu)秀的特性。
考慮到各個項目實際使用時寫法混亂,不統(tǒng)一。對Axios進(jì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: './',
//配置跨域請求
devServer: {
open: true, //是否自動打開瀏覽器
https: false, //是否開啟https
hotOnly: false,
proxy: { // 配置跨域
'/api': {
target: 'http://********', //請求接口域名
ws: true,
secure: false,
changOrigin: true, //是否允許跨越
pathRewrite: {
'^/api': ''
}
}
},
before: app => { }
}
}
4. 在src子目錄下的api文件夾下創(chuàng)建api.js文件進(jìn)行簡單的封裝axios
import axios from 'axios'
//這里引用了element的loading全屏加載
import { Loading } from "element-ui";
const service = axios.create({
baseURL: '/',
timeout: 30000 // 設(shè)置請求超時時間
})
let loading = "";
// 請求攔截器
service.interceptors.request.use(
(config) => {
// 在請求發(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"
// 讓每個請求攜帶token-- ['X-Token']為自定義key 請根據(jù)實際情況自行修改
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 返回數(shù)據(jù)中的 data
// loadingInstance.close();
const dataAxios = response.data
// 這個狀態(tài)碼是和后端約定的
return dataAxios
},
(error) => {
return Promise.reject(error)
}
)
export default service
5. 在api文件夾下創(chuàng)建http文件
// 引入封裝好的axios
// ps:如果沒有封裝,正常引入axios即可
import axios from "./api";
// /api為配置跨域的路徑變量
let reportUpload= '/api/report/upload'
export const Upload= () => {
return axios.get( reportUpload )
}
6. 在頁面中調(diào)用接口
// 引入封裝好的接口
import { Upload} from "@/api/http.js";
// 調(diào)用時使用
async Upload() {
let { result } = await getlist ();
console.log(result)
},
總結(jié)
到此這篇關(guān)于vue中axios封裝使用的文章就介紹到這了,更多相關(guān)vue axios封裝使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue使用css-rcurlyexpected等less報錯問題
這篇文章主要介紹了vue使用css-rcurlyexpected等less報錯問題,具有很的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-10-10
基于ElementUI中Table嵌套實現(xiàn)多選的示例代碼
這篇文章主要介紹了基于ElementUI中Table嵌套實現(xiàn)多選的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03

