来抄作业
先是对于axios的实例封装以及token在拦截器的处理
import axios, { AxiosRequestConfig } from 'axios'
import { createBrowserHistory } from 'history'
const history = createBrowserHistory()
//接口地址前缀
const baseApiUrl:string = '/api'
//错误标识
let isErr = true
//token前缀(也可以没有)
const PREFIX_TOKEN = 'Bearer'
//返回错误说明和处理
let errorHandler = (error:any) =>{
const response = error.response
let status,errorText,timer
if(response){
status = response.status
errorText = codeMessage[response.status]
}else if(error.code === 'CCC'){ //code是与后台商议好后的值,自行更改
status = ''
errorText = '服务器连接失败,请尝试重新登陆或联系相关服务人员'
}
if(isErr){
isErr = false
clearTimeout(timer)
//弹出错误信息
message.error(errorText)
timer = setTimerout(()=>{
isErr = true
},1000)
}
return
}
//创建axios实例
let instance = axios.create({
baseURL: baseApiUrl, //请求头地址
timeout: 30000, //指定请求超时毫秒数
headers: {
//设置头部信息,也可不设,一般默认
'Content-Type': 'application/json;charset=UTF-8',
'X-Reaquested-With': 'XMLHttpRequest'
},
withCredentials: false //表示跨域请求时是否需要使用凭证
})
//添加请求拦截器
instance.interceptors.request.use(
(config) = >{
//如果本地储存中有token值,则设置headers头部token
const token = localStorage.getItem('token')
if(token){
//将token设置到headers中,header的key是Authorization
config.headers.Authorization = PREFIX_TOKEN + token
}
return config
},(error)=>{
return Promise.reject(error)
}
)
// 添加响应拦截器
instance.interceptors.response.use(
(response) => {
const status = response.data.result ? response.data.result.status : ''
//token过期时,重定向到登录页
//并删除session和local信息返回错误码
//没有权限一般都是401
if(status === '00') {
const error = {
response: {status: 401}
}
//取退出登陆前的路由
const prevLogoutPath = sessionStorage.getItem('prevLogoutPath')
//第一次没有,所以存下路由
if(!prevLogoutPath ){
sessionStorage.setItem('prevLogoutPath',history.location.pathname)
}
// 跳转到登陆页,删除用户信息和token
history.replace('/login')
localStorage.removeItem('useInfo')
localStorage.removeItem('token')
return Promise.reject(error)
}
return response
},(error) => {
return Promise.reject(error)
}
)
下面是对请求方法的封装
import axios,{AxiosError,AxiosRequestConfig,AxiosResponse,Canceler,CancelTokenSource} from 'axios'
export interface AjaxResponse{
request:()=>Promise<AxiosResponse> //Axios异步函数
cancel:Canceler //关联的cancel方法
}
const baseConfig={
validateStatus:function (status:number){
return status < 400
}
}
/**封装了基本报错与cancel逻辑的Axios请求*/
export const ajax = (config:AxiosRequestConfig):Promise<any>=>{
return new Promise<AxiosResponse<any>>((resolve,reject)=>{
axios({...baseConfig, ...config})
.then((response)=>{
if(response.request.responseType==='blob'){
resolve(response)
return
}
const data = response.data
//这里的code以现实后台为准
if(data.code==='0'){
//成功
resolve(data)
}else if(data.code==='A01000'){
//当token出现问题是跳到登陆页面
history.push('login')
}else{
//失败报错
message.error(data.msg)
reject(data)
}
}).catch((error:AxiosError<any>)=>{
reject(error.response?.data)
})
})
}
export function get(url:string,paramse?:any,source?:CancelTokenSource){
return ajax({
method:'get',
url,
params,
cancelToken:source?source.token:undefined
})
}
//get形式文件流
export function getResponseBlob(url:string,paramse?:any,source?:CancelTokenSource){
return ajax({
method:'get',
url,
params,
cancelToken:source?source.token:undefined
})
}
export function post(url:string,paramse?:any,source?:CancelTokenSource){
return ajax({
method:'post',
url,
params,
responseType:'blob',
cancelToken:source?source.token:undefined
})
}
//post形式文件流
export function postResponseBlob(url:string,paramse?:any,source?:CancelTokenSource){
return ajax({
method:'post',
url,
params,
responseType:'blob',
cancelToken:source?source.token:undefined
})
}
export function del(url:string,paramse?:any,source?:CancelTokenSource){
return ajax({
method:'delete',
url,
params,
cancelToken:source?source.token:undefined
})
}