1. vue安裝axios
npm install axios -S
或者
npm i axios -S
2. 在main.js進行全域引入
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檔案夾下創建api.js檔案進行簡單的封裝axios
import axios from 'axios'
//這里參考了element的loading全屏加載
import { Loading } from "element-ui";
const service = axios.create({
baseURL: '/',
timeout: 30000 // 設定請求超時時間
})
let loading = "";
// 請求攔截器
service.interceptors.request.use(
(config) => {
// 在請求發送之前做一些處理
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 請根據實際情況自行修改
if (token) {
config.headers['Authorization'] = token
}
return config
},
(error) => {
loading.close();
// 發送失敗
console.log(error)
return Promise.reject(error)
}
)
// 回應攔截器
service.interceptors.response.use(
(response) => {
loading.close();
// dataAxios 是 axios 回傳資料中的 data
// loadingInstance.close();
const dataAxios = response.data
// 這個狀態碼是和后端約定的
return dataAxios
},
(error) => {
return Promise.reject(error)
}
)
export default service
5. 在api檔案夾下創建http檔案
// 引入封裝好的axios
// ps:如果沒有封裝,正常引入axios即可
import axios from "./api";
// /api為配置跨域的路徑變數
let reportUpload= '/api/report/upload'
export const Upload= () => {
return axios.get( reportUpload )
}
6. 在頁面中呼叫介面
// 引入封裝好的介面
import { Upload} from "@/api/http.js";
// 呼叫時使用
async Upload() {
let { result } = await getlist ();
console.log(result)
},
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/265407.html
標籤:其他
下一篇:宏任務與微任務和事件回圈
