axios 配置
安装axios和Qs
npm install axios --save
npm install --save axios vue-axios qs
import axios from 'axios'
import qs from 'qs' //qs 用来解决vue中post请求以 a=a&b=b 的格式(详情)
配置
import Vue from 'vue'
import axios from "axios";
import Qs from "qs";
//axios 配置 [封装axios]
axios.defaults.withCredentials = true; //vue前后端分离解决每次请求session都会变的问题
axios.defaults.transformRequest = [function(data) {
// if (data.toString() == "[object FormData]") {
// return data;
// } else {
// return Qs.stringify(data)
// }
return Qs.stringify(data)
}];
let host
host = process.env.NODE_ENV === 'development' ? '/' : 'http://abex.jinjifuweng.com/' // 根据 process.env.NODE_ENV 的值判断当前是什么环境
// host = process.env.NODE_ENV === 'production' ? '/' : 'http://abex.jinjifuweng.com/' // 根据 process.env.NODE_ENV 的值判断当前是什么环境
const instance = axios.create({
baseURL: host,
timeout: 10000,
withCredentials: true,
})
// 添加响应拦截器
instance.interceptors.response.use(function(response) {
// 对响应数据做点什么
if (response.data.status == -1) {
// Vue.prototype.$message({
// message: response.data.msg,
// type: "error",
// duration: 2000
// });
console.log(response.data.status);
} else if (response.data.status == 0) {
console.log(response.data.status);
}
return response;
}, function(error) {
// 对响应错误做点什么
// Vue.prototype.$message({
// message: "请求失败",
// type: "error",
// duration: 2000
// });
return Promise.reject(error);
});
Vue.prototype.$http = instance;
import './http/http.js'
使用
this.$http.post(url,data).then(res=>{})
this.$http.get(url).then(res=>{})