vue网络请求
post网络请求
import axios from 'axios'
import {ElMessage, ElLoading} from "element-plus"
import { nextTick } from "vue"
import JSONbig from 'json-bigint'
import { userToken } from "@/constants/Constant.js";
const defaultConfig = {
baseURL: import.meta.env.VITE_BASE_URL,
timeout: 2 * 60 * 1000,
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
transitional: {
forcedJSONParsing: false
},
transformResponse: (data) => {
try {
return JSONbig.parse(data)
} catch (err) {
return data
}
}
};
const instance = axios.create({
...defaultConfig,
})
instance.interceptors.request.use((config) => {
// 实时动态设置登陆用户token
config.headers.Authorization = userToken();
return config;
});
export async function postReq(path, param, config, success, fail) {
return await instance.post(
path,
param || {},
config,
).then(success, fail)
}
/**
*
* @param {*} callback 只返回成功后的数据
*/
export function basePostReq(path, param, callback) {
sendPostReq(path, param, null, true, true, true, callback)
}
/**
*
* @param {*} isShowLoading 是否显示loading
* @param {*} isShowError 是否显示报错
* @param {*} isOnlyData 是否只返回有用的数据
* @param {*} callback 只返回成功后的数据
*/
export function sendPostReq(path, param, config, isShowLoading, isShowError, isOnlyData, callback) {
var loading = null
if (isShowLoading) {
loading = ElLoading.service({
lock: true,
text: '请稍等...',
background: 'rgba(0, 0, 0, 0.7)'
})
}
postReq(path, param, config, (res)=> {
if (loading) {
nextTick(() => {
loading.close()
})
}
if (res.data instanceof Blob) {
if (res.data.type == 'application/json') {
const reader = new FileReader()
reader.readAsText(res.data, 'utf-8')
reader.onload = function() {
try {
const blobData = JSON.parse(reader.result)
if (!blobData.code || blobData.code != 200) {
if (isShowError) {
ElMessage({
showClose: true,
message: blobData.message || '请求失败',
duration: 0,
type: 'error'
})
}
return
}
if (isOnlyData && blobData) {
if (callback) {
callback(blobData.data)
}
} else {
if (callback) {
callback(blobData)
}
}
} catch (e) {
ElMessage({
showClose: true,
message: "json解析失败:" + e.toString(),
duration: 0,
type: 'error'
})
}
}
} else {
if (callback) {
callback(res.data)
}
}
return
}
if (!res.data.code || res.data.code != 200) {
if (isShowError) {
ElMessage({
showClose: true,
message: res.data.message || '请求失败',
duration: 0,
type: 'error'
})
}
return
}
if (isOnlyData && res.data) {
if (callback) {
callback(res.data.data)
}
} else {
if (callback) {
callback(res.data)
}
}
}, (err)=> {
if (loading) {
nextTick(() => {
loading.close()
})
}
ElMessage({
showClose: true,
message: err.code +', ' + err.message,
duration: 0,
type: 'error'
})
})
}
原文地址:https://blog.csdn.net/liu1shi/article/details/140625502
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!