1.request.js
import axios from "axios";
import { ElMessage } from 'element-plus'
import router from "../routers";
import config from "../config";
const TOKEN_ERR = "token失效了"
const NET_WORK = "网络有问题,请检查一下网络把"
const service = axios.create({
baseURL: config.baseApi,
timeout: 8000
})
service.interceptors.request.use((req) => {
const headers = req.headers
if (!headers.Authorization) {
headers.Authorization = "token_val"
}
return req
}, (error) => {
Promise.reject(error)
})
service.interceptors.response.use((res) => {
const { code, data, msg } = res.data
if (code === 200) {
return data
} else if (code === 401) {
ElMessage.error(TOKEN_ERR)
setTimeout(() => {
router.push('/login')
}, 1500)
return Promise.reject(TOKEN_ERR)
} else {
ElMessage.error(msg || NET_WORK)
return Promise.reject(msg || NET_WORK)
}
}, (error) => {
Promise.reject(error)
})
function request(options) {
options.method = options.method || 'get'
if (options.method.toLowerCase() === "get") {
options.params = options.data
}
if (config.env === 'prod') {
service.defaults.baseURL = config.baseApi
} else {
service.defaults.baseURL = config.mock ? config.mockApi : config.baseApi
}
return service(options)
}
['get', 'post', 'put', 'delete', 'patch'].forEach(v => {
request[v] = (url, data, options) => {
return request({
url,
data,
method: v,
...options
})
}
})
export default request
2. main.js
import { createApp } from 'vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import request from './utils/request'
import App from './App.vue'
import router from './routers'
const app = createApp(App)
app.config.globalProperties.$request = request
app.use(router).use(ElementPlus).mount('#app')
3. 使用
this.$request.get('/login', {name: 'jack'}).then(v=> {
console.log(22,v);
})
|