123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117 |
- import axios from 'axios'
- // import store from '@/store'
- import qs from 'qs'
- const service = axios.create({
- timeout: 30000 // 请求超时时间
- })
- function isJSON (val) {
- if (typeof val !== 'string') {
- return false
- }
- try {
- const obj = JSON.parse(val)
- if (Object.prototype.toString.call(obj) === '[object Object]') {
- return true
- } else {
- return false
- }
- } catch (e) {
- return false
- }
- }
- service.interceptors.request.use(
- config => {
- // if (!config.headers.Authorization) {
- // config.headers.Authorization = token // 让每个请求携带自定义token 请根据实际情况自行修改
- // }
- if (config.headers['Content-Type'] === 'application/x-www-form-urlencoded' && config.data && Object.prototype.toString.call(config.data) === '[object Object]') {
- config.data = qs.stringify(config.data)
- }
- return config
- },
- err => {
- return Promise.reject(err)
- }
- )
- // respone拦截器 处理数据
- service.interceptors.response.use(
- response => {
- const { data } = response
- const resData = isJSON(data) ? JSON.parse(data) : data
- if (typeof resData === 'object') {
- return resData
- } else {
- // 针对返回 res 是二进制数据流
- return response
- }
- },
- error => {
- return Promise.reject(error)
- }
- )
- export function request (_param) {
- const {
- method = 'get',
- // `responseType` 表示服务器响应的数据类型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
- responseType = 'json', // 默认的
- headers = {},
- url = '',
- params,
- data,
- ...otherData
- } = _param
- if (!url) {
- return new Promise((resolve, reject) => {
- // eslint-disable-next-line prefer-promise-reject-errors
- reject('url is null')
- })
- }
- const _method = method.toLowerCase()
- console.info('_param', _param)
- if (_method === 'get') {
- return axios({
- responseType,
- url,
- headers,
- method,
- params: params || data || otherData
- })
- }
- if (_method === 'post') {
- // 处理
- // if (!headers.hasOwnProperty('Content-Type')) {
- // headers["Content-Type"] = "application/x-www-form-urlencoded"
- // }
- if (params && data) {
- return axios({
- responseType,
- url,
- headers,
- method,
- params,
- data
- })
- } else {
- const { start, limit, ...resetData } = otherData
- return axios({
- responseType,
- url,
- headers,
- method,
- params: params || { start, limit },
- data: data || resetData
- })
- }
- }
- }
- export default service
|