封装:
目录结构:src/utils/request.js, 没有就自己建一个
import axios from 'axios' import { Message } from 'element-ui' // create an axios instance const service = axios.create({ baseURL: '/gateway', //添加于请求路径前 timeout: 5000 // request timeout }) service.interceptors.request.use( //请求拦截 config => { const token = window.localStorage.getItem('token') if (token) { config.headers['autel-token'] = token //在请求之前,像 headers 里面携带token } // Do something before request is sent if ( config.applicationType !== 'JSON' && config.url.indexOf('community-attachment') === -1 ) { //对 post 请求 或 put 请求的数据做 JSON 转换 if (config.method === 'post' || config.method === 'put') { let _data = '' for (const it in config.data) { const value = config.data[it] === null ? '' : config.data[it] _data += encodeURIComponent(it) + '=' + encodeURIComponent(value) + '&' } config.data = _data } } return config }, error => { // Do something with request error return Promise.reject(error) } ) service.interceptors.response.use( //对请求回来的数据做统一错误处理 response => { const res = response if (res.data.code !== 1) { Message({ message: res.data.message || '不明错误', type: 'error', duration: 5 * 1000 }) } // if the custom code is not 20000, it is judged as an error. if (res.status !== 200) { Message({ message: res.message || '不明错误', type: 'error', duration: 5 * 1000 }) return Promise.reject(new Error(res.message || 'Error')) } else { return res } }, error => { console.log('err' + error) // for debug Message({ message: error.message, type: 'error', duration: 5 * 1000 }) return Promise.reject(error) } ) export default service
跨域, 在 vue.config.js 里配置
const path = require('path') const resolve = dir => { return path.join(__dirname, dir) } module.exports = { devServer: { host: '0.0.0.0', port: 8080, proxy: { '/api': { target: 'http://autel-cloud-xxxx-dev.com', changeOrigin: true } } }, chainWebpack: config => { config.resolve.alias .set('@', resolve('src')) .set('@API', resolve('src/api')) .set('@C', resolve('src/components')) .set('@U', resolve('src/utils')) .set('@V', resolve('src/views')) .set('@ATS', resolve('src/assets')) } }
使用
src/api/menu.js
import request from '@/utils/request' //添加菜单 export function addOrCompileMenu(data) { return request({ url: '/api/admin/menu/saveMenu', method: 'post', applicationType: 'JSON', //这一段表示,是post 请求,就将 请求参数转换成 JSON 格式 data }) }
src/views/menu.vue
import { getMenuList } from '@/api/menu' methods: { getMenuList({}).then(res => { if (res.status === 200) { this.list = res.data.data.menuVoList } }) }