axios.js
import Vue from 'vue'
import axios from 'axios'
import apiConfig from '@/config/api.config'
import { TOKEN_KEY } from '@/data/constant'
import FieldStyleUtils from '@/utils/field-style'
axios.defaults.baseURL = apiConfig.apiHost
axios.defaults.headers.common['Accept'] = 'application/json'
// request拦截器
axios.interceptors.request.use(
config => {
const token = Vue.ls.get(TOKEN_KEY)
const role = Vue.ls.get('X-Role')
if (token) {
config.headers['X-Token'] = token // 让每个请求携带自定义 token
}
if (role) {
config.headers['X-Role'] = role
}
config.data = FieldStyleUtils.toSnakecase(config.data)
config.params = FieldStyleUtils.toSnakecase(config.params)
return config
},
error => {
return Promise.reject(error)
}
)
// response 拦截器
axios.interceptors.response.use(
response => {
return FieldStyleUtils.toCamelcase(response.data)
},
error => {
let data
if (error.response) {
data = error.response.data
if (error.response.status >= 500) {
data = {
code: '500',
message: '服务器内部发生了错误'
}
} else if (error.response.status === 401) {
Vue.ls.remove(TOKEN_KEY)
}
} else {
data = {
message: '网络错误'
}
}
return Promise.reject(data || error)
}
)
const setHeaderToken = (token) => {
axios.defaults.headers.common['X-Token'] = token
}
const clearHeaderToken = () => {
delete axios.defaults.headers.common['X-Token']
Vue.ls.clear()
window.location.reload()
}
export default axios
export {
setHeaderToken,
clearHeaderToken
}
api
import axios from '@/utils/axios'
import Base from '../base'
const path = '/technologies'
class Technology extends Base {
constructor (attrs = {}) {
super(attrs)
}
static async list (params) {
const { technologies, count } = await axios.get(path, { params })
const list = technologies.map(item => new Technology(item))
return { technologies: list, count }
}
static async detail (id) {
const { technology: attrs } = await axios.get(`${path}/${id}`)
return new Technology(attrs)
}
}
export default Technology
调用
async fetchList () {
this.loading = true
try {
this.pagination.pageNo++
const params = {
text: this.keyword,
...this.pagination
}
const { technologies } = await Technology.list(params)
if (technologies.length > 0) {
this.technologies.push(...technologies)
} else {
this.finished = true
this.pagination.pageNo--
}
} catch ({ message = '获取成果列表失败' }) {
this.error = true
this.$toast.fail(message)
} finally {
this.loading = false
}
}