// request.ts
import { Request, Result } from 'lbl-request'
import { AxiosRequestConfig, AxiosResponse } from 'axios'
export const request = new Request({
// 业务域名
baseURL: 'https://lbaxios.com/api',
// 返回 json 的大小写转换:'pascal' | 'camel' | 'none'
convertCase: 'camel',
// 成功条件
successCondition: (result: Result) => {
return result.code === 0
},
// 发生异常时处理
onError: (result: Result, toastError: boolean) => {
console.log(`----- ${result.url} 接口报错 -----`)
console.log(result)
if (result.status === 401) {
Util.toast.error('登录状态失效,请重新登录')
setTimeout(() => {
StoreUser.logout()
}, 1000)
} else if (toastError) {
Util.toast.error(result.message)
}
},
// 请求头混入
mixinHeader: (config: AxiosRequestConfig, isBusinessDomain: boolean) => {
if (!isBusinessDomain) return config
const token = Util.token.getToken()
if (token) {
config.headers.common['Authorization'] = token
}
config.headers.common['Accept-Language'] = Util.i18n.getLang()
return config
},
// 响应内容转换为 Result
responseFormat: (result: Result, response: AxiosResponse) => {
const data = response.data
result.code = data.code
result.message = data.message
result.data = data.data
return result
}
})
// api/user.ts
import { request } from './request'
export async function login() {
const res = await request.post('/user/login', {
username: '123456',
password: 123456
})
const { token } = res.hasSuccess()
Util.token.setToken(token)
}