定义 request.js
文件,我们可以放在项目的公共文件夹下,我放的位置在 src/utils/request.js
下面是逻辑代码:
import axios from 'axios'
import Cookies from 'js-cookie'
import router from '@/router'
import qs from 'qs' // 需要 npm install qs 安装
import { clearLoginInfo } from '@/utils'
import isPlainObject from 'lodash/isPlainObject' // 需要 npm install lodash 安装
const http = axios.create({
baseURL: window.SITE_CONFIG['apiURL'], // 设置公共路径
timeout: 1000 * 180, // 设置请求超时时间
withCredentials: true
})
/**
* 请求拦截
*/
http.interceptors.request.use(config => {
config.headers['Accept-Language'] = Cookies.get('language') || 'zh-CN'
config.headers['tenantCode'] = Cookies.get('tenantCode') || ''
if (config.url !== '/auth/oauth/token') {
config.headers['Authorization'] = 'Bearer ' + Cookies.get('access_token') || ''
}
// 默认参数
var defaults = {}
// 防止缓存,GET请求默认带_t参数
if (config.method === 'get') {
config.params = {
...config.params,
...{ '_t': new Date().getTime() }
}
}
if (isPlainObject(config.params)) {
config.params = {
...defaults,
...config.params
}
}
if (isPlainObject(config.data)) {
config.data = {
...defaults,
...config.data
}
if (/^application\/x-www-form-urlencoded/.test(config.headers['content-type'])) {
config.data = qs.stringify(config.data)
}
}
// get序列化
config.paramsSerializer = function (params) {
return qs.stringify(params, { arrayFormat: 'repeat' })
}
return config
}, error => {
return Promise.reject(error)
})
/**
* 响应拦截
*/
http.interceptors.response.use(response => {
if (response.data.code === 401 || response.data.code === 10001) {
clearLoginInfo()
router.replace({ name: 'login' })
return Promise.reject(response.data.msg)
}
return response
}, error => {
console.error(error)
return Promise.reject(error)
})
export default http
然后我们需要在 main.js
中全局挂在:
import http from '@/utils/request'
// 挂载全局
Vue.prototype.$http = http
使用方法:
<script>
export default {
data() {
dataList: []
},
created() {
this.init()
},
methods: {
init() {
// 请求参数
let param = {
id: this.dataForm.id,
name: this.dataForm.name,
}
// post请求直接写 param 即 this.$http.post('请求路径', param).then((res) => {})
this.$http.get('请求路径', { params: param }).then((res) => {
res = res.data
if(res.code == 500) return this.$message.error(res.msg)
this.dataList = res.data
console.log(this.dataList)
})
}
}
}
</script>
另外,post
、put
、delete
等请求方式只需要替换上面的 get
即可。注意 post
请求传参不需要对象用包括起来。