这个方法是面向vue-cli
的,所以在使用之前请先初始化好vue-cli
工程
配置代理
config/index.js
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/': {
target: 'http://168.0.0.158/', // 你请求的第三方接口
changeOrigin: true, // 在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题
pathRewrite: { // 路径重写,
'^/': '' // 替换target中的请求地址
}
}
},
使用
methods: {
login: function () {
var _this = this;
var url = "/mgmt/login.do"; // 这里就是刚才的config/index.js中的/api
// 或者使用以下代码也可
this.$axios({
method: "post",
url: url,
data:{
userName:'admin',
password:'21232f297a57a5a743894a0e4a801fc3'
}
})
.then(function (res) {
console.log(res);
let data = res.data;
if(data.retCode == 0){
_this.$router.push({path:'/helloworld'})
}
})
.catch(function (err) {
console.log(err);
});
}
}
实际效果
这里虽然请求的地址是localhost:8081
,但是实际上是请求的168.0.0.158:8080
一劳永逸(开发环境和生产环境)
1、新建src/request/config.js
//项目域名地址
const url = 'http://localhost:8086';
// const url = 'http://168.0.0.119:8080';
let ROOT;
//由于封装的axios请求中,会将ROOT打包进去,为了方便之后不再更改,判断了当前环境,而生成的不同的ROOT
if (process.env.NODE_ENV === 'development') {
//开发环境下的代理地址,解决本地跨域跨域,配置在config目录下的index.js dev.proxyTable中
ROOT = "/apis
} else {
//生产环境下的地址
ROOT = url;
}
exports.PROXYROOT = url; //代理指向地址
exports.ROOT = ROOT;
2、新建config/proxyConfig.js
const config = require("../src/request/config"); //路径你们改下
module.exports = {
proxy: { [config.ROOT] : { //将www.exaple.com印射为/apis
target: config.PROXYROOT,
// 接口域名
secure: false,
// 如果是https接口,需要配置这个参数
changeOrigin: true,
//是否跨域
pathRewrite: { [` ^ $ {
config.ROOT
}`] : '' //需要rewrite的
}
}
3、修改config/index.js
var proxyConfig = require('./proxyConfig')
module.exports = {
dev: {
proxyTable: proxyConfig.proxy,//
}
}