默认配置
import axios from 'axios'
axios.defaults.withCredentials = true // 是否在跨域请求中携带凭证(如 cookie)
axios.defaults.timeout = 10000 // 设置超时时间
axios.defaults.headers.common['Content-Type'] = 'application/json' // common全局通用配置
axios.defaults.headers['X-Requested-With'] = 'XMLHttpRequest'
const context = 'fuwuqi'
const apis = {
/**
* @Description: 用户管理
*/
getUserInfo: `${context}/user/getUserInfo`
}
export { apis, axios }
请求拦截
import { useSystemStore } from '@/stores/system'
axios.interceptors.request.use(
function (config) {
config.headers['test'] = 0 // 1:开 0:关
config.headers['tenantId'] = systemStore.tenantId // 租户id
return config
},
function (error) {
return Promise.reject(error)
}
)
响应拦截
axios.interceptors.response.use(
function (response) {
if (response && response.data && (response.data.flag || response.data.success)) {
// 具体情况修改上述的条件
if (response.data.ret !== 302) {
return response.data
}
localStorage.setItem('login', false)
console.log(('接口302' + response?.data?.redirectUrl))
if (import.meta.env.PROD && response?.data?.redirectUrl) {
//判断是否在生产环境import.meta.env.PROD
window.location.href = response.data.redirectUrl
}
return null
} else {
// 直接返回的数据,如文件等
if (Object.prototype.toString.call(response.data) === '[object Blob]') {
return response
}
ElMessage.error(response?.data?.message ?? '请求接口错误!')
return null
}
},
function (error) {
ElMessage.error(error.message || '服务器出错!')
return Promise.reject(error)
}
)
使用实例1—正常情况(成功或失败)
具体使用get、post等,可参考文章 axios的get和post请求传headers、query、body等参数
import { axios, apis } from '@/request'
async function save(id) {
const result = await axios.post(
apis.saveInfo,
{ id: id},
{
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}
// 若请求头为默认的'application/json' , 则不用传上述的对象
)
if (result) {
console.log('接口请求成功')
}
// 错误会直接拦截,此时返回的result为null
}
使用实例2—返回为文件流
此时result的data为文件流
import { axios, apis } from '@/request'
async function save(id) {
const result = await axios.post(
apis.download,
{ id: id},
{ responseType: 'blob' }
)
if (result.data) {
console.log('接口请求成功')
// 下载文件
const blob = result.data;// 可以通过 new Blob([{id:'121'}]) 生成blob
const elink = document.createElement('a') // 创建a标签
elink.href = window.URL.createObjectURL(blob)
elink.download = 'fileName.txt' // 文件名
elink.style.display = 'none'
document.body.appendChild(elink)
// link.target = '_blank' // 打开新的标签页
elink.click()
URL.revokeObjectURL(elink.href)
document.body.removeChild(elink)
}
}