1、在main.js同级目录下 新建api.js
import axios from 'axios';
import qs from 'qs';
//设置默认请求方式,指定Content-Type
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
const instance = axios.create({
baseURL: '/api',
timeout: 3000,
});
//vue全局扩展方法接口
function install(Vue) {
Vue.prototype.$ajax = {
post,
get
};
}
//post请求方法,并根据不同请求类型传入指定的 headers
async function post(url, opts = {}, headers) {
var result = {};
try {
result = await instance.post(url, qs.stringify(opts), headers);
} catch (e) {
console.log(e)
result = e.response || {
data: null
};
}
return result.data;
}
async function get(url, type, opts = {}) {
var result = {};
try {
result = await instance.get(url, opts);
} catch (e) {
console.log(e)
result = e.response || {
data: null
};
}
return result.data;
}
export default {
install
}
2、在 main.js中全局引用即可
//在main.js中添加
import api from "./api";
Vue.use(api);
3、webpack 代理
webpack.base.config.js,在module.exports 中添加
devServer: {
historyApiFallback: true,
hot: true,
inline: true,
stats: { colors: true },
proxy: {
"/api": { //axios中给请求添加 /api,用于代理标识
target: 'http://1.1.1.1:8081', //目标地址
secure: false, // 接受 运行在 https 上的服务
changeOrigin: true,
pathRewrite:{'^/api':''}, //重写请求路径,把/api用空替换掉
}
},
},
4、使用,(有朋友再问怎么使用,就补充一下)
因为方法是扩展的vue原型上的,直接使用this.$ajax即可。
/**
第一个参数:请求接口路径 必须
第二个参数:请求体data 非必须
第三个参数:设置Content-Type 非必须
**/
配合async await 使用更佳
let result = await this.$ajax.post("url", data
,{ "Content-Type": "application/json"});
let result = await this.$ajax.get("url", data
,{ "Content-Type": "application/json"});