1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 |
- import axios from 'axios'
- import { Message } from 'element-ui'
- import qs from 'qs'
-
- const Axios = axios.create({
- timeout: 60000,
- responseType: 'json',
- withCredentials: true,
- headers: {
- 'Content-Type': 'multipart/form-data'
- }
- })
-
- Axios.interceptors.request.use((config) => {
- // 处理请求data,若为get请求,拼到url后面,若为post请求,直接添加到body中
- let data = qs.stringify(config.data)
- if (config.method === 'get' || config.method === 'GET') {
- // 判断是通过斜杠传参还是通过query传参
- if (config.url.indexOf(':') > -1) {
- if (typeof config.data === 'object') {
- config.url = Object.keys(config.data).reduce((url, k) => { // 此方法对每个元素进行处理
- const re = new RegExp(`:${k}(?!w)`, 'i')
- return url.replace(re, config.data[k])
- }, config.url)
- } else {
- config.url = config.url.slice(0, config.url.indexOf(':')) + data
- }
- } else {
- if (data) {
- config.url += '?' + data
- }
- }
- }
- let fm = new FormData()
- for (let k in config.data) {
- if (Array.isArray(config.data[k])) {
- fm.append(k, ...config.data[k].map(v => `${k}=${encodeURIComponent(v)}`))
- } else {
- fm.append(k, config.data[k])
- }
- }
- config.data = fm
- return config
- }, (error) => {
- console.log(error)
- })
-
- Axios.interceptors.response.use((res) => {
- if (res.data.code === 200) {
- return res.data.result
- } else {
- Message({
- message: res.data.message,
- type: 'error'
- })
- return res.data
- }
- }, (error) => {
- console.log(error)
- })
-
- export default Axios
|