axios 封装(单独引入element UI js文件、css文件) 作者:马育民 • 2024-04-26 23:39 • 阅读:10058 # 说明 本案例适合在 `.html` 文件中,引入 `element UI` 的js文件、css文件,如下: ``` ``` ### 封装代码 ``` // 全局路径 const url_all = { 'DEV': '/', // 开发 // 'DEV': 'http://192.168.0.203:8082/airship', // 开发 'PRD': '/airship', // 生产环境。不能是 ./ ,因为前端路径会跟着改变 } export let BASEURL = url_all['DEV'] // vue对象,在下面要使用 element UI 窗口 let vueObject ; // create an axios instance const request = axios.create({ baseURL: BASEURL, // url = base url + request url // withCredentials: true, // send cookies when cross-domain requests timeout: 5000 // request timeout }) // request interceptor //request.interceptors.request.use( // config => { // // do something before request is sent // // if (store.getters.token) { // // let each request carry token // // ['X-Token'] is a custom headers key // // please modify it according to the actual situation // config.headers['X-Token'] = getToken() // } // return config // }, // error => { // // do something with request error // console.log(error) // for debug // return Promise.reject(error) // } //) // response interceptor request.interceptors.response.use( /** * If you want to get http information such as headers or status * Please return response => response */ /** * Determine the request status by custom code * Here is just an example * You can also judge the status by HTTP Status Code */ response => { const res = response.data // console.log("res:",res) // if the custom code is not 20000, it is judged as an error. if(res.code == 0){ return res }else if(res.code == 100){ location.href='/static/login.html' }else{ vueObject.$message({ message: res.msg || 'Error', type: 'error', duration: 5 * 1000 }) return Promise.reject(new Error(res.msg || 'Error')) } }, error => { console.log('err' + error) // for debug vueObject.$message({ message: error.message, type: 'error', duration: 5 * 1000 }) return Promise.reject(error) } ) /** * post 请求 * 数据以json格式发送到服务器 */ export const post =(vue,url,data)=>{ vueObject = vue return request({ url: url, method: 'post', data }) } /** * get请求 * 请求头 content-type 的值是 application/x-www-form-urlencoded */ export const get =(vue,url,data)=>{ vueObject = vue return request({ url: url, method: 'get', params: data }) } ``` 原文出处:https://malaoshi.top/show_1IX7aBubP4cV.html