vue axios 请求二次封装
/** * 封装get方法 * @param url * @param data * @returns {Promise} */ export function get(url, params) { return new Promise((resolve, reject) => { axios.get(url, { params: params }) .then(response => { resolve(response.data); }) .catch(err => { reject(err) }) }) } /** * 封装post请求 * @param url * @param params * @returns {Promise} */ // Form Data // headers: { // "Content-Type": 'application/x-www-form-urlencoded; charset=UTF-8' // } // Form Data Request payload
//当headers为 json时是 request 方式发送请求 但是如果你们的后台是formData的方式接口 就传一个header进来 就可以 formData 需要qs序列化
//因为我们后台是json接受的比较多 所以json在我这里是默认 可以根据自己的情况修改 这个需要json转字符串不然是乱码的
export function post(url, params = {}, headers) { return new Promise((resolve, reject) => { if (headers == undefined) { axios.post(url, JSON.stringify(params), { headers: { "Content-Type": "application/json;charset=UTF-8" } }) .then(res => { resolve(res.data); }) .catch(err => { reject(err.data) }) } else { axios.post(url, QS.stringify(params), headers) .then(res => { resolve(res.data); }) .catch(err => { reject(err.data) }) } }); }
/** * 封装patch请求 * @param url * @param data * @returns {Promise} */ export function patch(url, data = {}) { return new Promise((resolve, reject) => { axios.patch(url, data) .then(response => { resolve(response.data); }, err => { reject(err) }) }) } /** * 封装put请求 * @param url * @param data * @returns {Promise} */ export function put(url, data = {}) { return new Promise((resolve, reject) => { axios.put(url, data) .then(response => { resolve(response.data); }, err => { reject(err) }) }) }
main.js中
import { post, get, patch, put, } from './assets/utils/http' //定义全局变量 Vue.prototype.$post = post; Vue.prototype.$get = get; Vue.prototype.$patch = patch; Vue.prototype.$put = put;
使用
this.$get("/role/getAllRole",{}).then(res => {});
this.$post("/judge/editJudgeInfoRole", { oid: this.rowData.oid, roleid: this.roleid }).then(res => {});
拦截
全部代码
import axios from 'axios' import QS from "qs" import store from "@/store/index" import router from '@/router/index' import { mapState, mapMutations } from "vuex"; import { Message } from 'element-ui'; axios.defaults.timeout = 10000; axios.defaults.baseURL = process.env.API_ROOT; axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'; axios.defaults.headers.common['Authorization'] = store.state.token ? store.state.token : localStorage.token; axios.interceptors.request.use( config => { config.headers = { 'Authorization': store.state.token ? store.state.token : localStorage.token } return config; }, error => { return Promise.reject(err); } ); //http response 拦截器 axios.interceptors.response.use( response => { }, error => { return Promise.reject(error) } )