突然间想做一个VUE的请求封装的帖子,然后从找了很多个开源的请求封装,然后再结合自己理解就发了一个帖子。
import axios from 'axios'
import { get, isEmpty } from 'lodash'
import qs from 'qs'
import util from '../util/util'
function createService() {
const service = axios.create()
service.interceptors.request.use(
config => config,
error => {
return Promise.reject(error)
}
)
service.interceptors.response.use(
response => {
if (response.data.code === undefined) {
return response.data
}
switch (response.data.code) {
case 0: return response.data.data
case 401: throw new Error('请重新登录')
default: throw new Error(`${response.data.msg}: ${response.config.url}`)
}
},
error => {
const status = get(error, 'response.status')
switch (status) {
case 400: error.message = '请求错误'; break
case 401: error.message = '未授权,请登录'; break
case 403: error.message = '拒绝访问'; break
case 404: error.message = `请求地址出错: ${error.response.config.url}`; break
case 408: error.message = '请求超时'; break
case 500: error.message = '服务器内部错误'; break
case 501: error.message = '服务未实现'; break
case 502: error.message = '网关错误'; break
case 503: error.message = '服务不可用'; break
case 504: error.message = '网关超时'; break
case 505: error.message = 'HTTP版本不受支持'; break
default: break
}
throw error
}
)
return service
}
function stringify(data) {
return qs.stringify(data, { allowDots: true, encode: false })
}
function createRequest(service) {
return function (config) {
const token = util.cookies.get('token')
const configDefault = {
headers: {
Authorization: token,
'Content-Type': get(config, 'headers.Content-Type', 'application/json')
},
timeout: 5000,
baseURL: process.env.VUE_APP_API,
data: {}
}
const option = Object.assign(configDefault, config)
if (!isEmpty(option.params)) {
option.url = option.url + '?' + stringify(option.params)
option.params = {}
}
if (!isEmpty(option.data) && option.headers['Content-Type'] === 'application/x-www-form-urlencoded') {
option.data = stringify(option.data)
}
return service(option)
}
}
export const service = createService()
export const request = createRequest(service)
import { request } from '../request'
export function postLogin(url, data = {}) {
return request({
url: url,
method: 'post',
data
})
}