vue修改proxyTable解决跨域请求,报404的问题及解决
作者:bdmh
vue修改proxyTable解决跨域请求,报404解决
环境
vue前端和后端接口部署在同一台机器。
vue服务部署在 http://localhost:8081,后台服务部署在 http://localhost:8080,可以看到端口是不一样的,在vue通过以下方式请求:
export default {
name:'Condition',
data(){
return{
options:[]
}
},
created:function(){
this.getdata();
},
methods:{
getdata(){
this.$axios({
method:'get',
url:'http://localhost:8080/college/getcollege'
}).then(resp => {
this.options = resp.data.data.list;
console.log(resp.data);
}).catch(resp => {
console.log('请求失败:'+resp.status+','+resp.statusText);
});
}
}
}因为端口不一致,axios就会认为是跨域了,所以就会报错:
Access to XMLHttpRequest at 'http://localhost:8080/college/getcollege' from origin 'http://localhost:8081' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. [http://localhost:8081/#/]
这里只介绍通过修改config中的index.js文件中的proxyTable的配置去解决的方法。在网上随便搜一下,基本都是如下的内容:
proxyTable: {
"/api": {
target: "http://localhost:8080",
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
},修改后,绝大部分人都会遇到404的错误,如下:
the server responded with a status of 404 (Not Found) [http://localhost:8081/college/getcollege
奇怪吧,明明设置了代理,怎么没有生效呢?不是方法不对,而是没有理解proxyTable中节点的意义。
其中的“api”节点,这是路由,系统会去根据这个匹配你的地址,匹配上才会生效,proxyTable中可以指定多个路由,一开始会认为这个是规定格式,所以都不会去修改,除非你的api部署地址是这样的“http://localhost:8080/api/*”,恭喜你,你的问题可能解决了,但是根据我的地址是“http://localhost:8080/college/getcollege”,就完蛋了,那么该怎么改,如下:
proxyTable: {
//碰到college路由就会起作用了
"/college": {
target: "http://localhost:8080",
changeOrigin: true,
//重定向,一般可以不用写,或者值写出空''
pathRewrite: {
'^/college': '/college'
}
}
},OK,问题解决。
vue的proxyTable跨域处理
当我们请求的地址出现不符合同源策略的时候,就会出现跨域的问题,这里仅对在vue 项目中使用axions请求跨域做记录
跨域报错截图

案例:请求"https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=10"中的数据
分析
问号(?)之前的为我们要请求的后端地址,包含协议、域名、地址等等问号(?)之后的内容为我们需要提交的参数,参数之间用&连接
解决方案
1、配置跨域
在项目中与src同级下有一个config文件夹,打开这个文件夹中的index.js文件

在index.js文件的 module.exports 中的 dev 中的 proxyTable 进行跨域配置
module.exports = {
dev: {
...
proxyTable: {
'/api': { //这里的/api,就是我们在target里写的要请求的后端接口
target: 'https://cn.bing.com/',
//要请求的后端接口地址,一般写多个数据接口的共同内容,后面的地址根据请求数据的不同,在请求的时候再拼接上就好
changeOrigin: true, //是否允许跨越
pathRewrite: {
'^/api': '', //重写,一般情况下不需要
}
}
},
// Various Dev Server settings
host: 'localhost', // can be overwritten by process.env.HOST
port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be
},
...
}2、使用axios请求数据
methods:{
getData(){
axios
.get("/api/HPImageArchive.aspx", {
params: {
format: "js",
idx: 0,
n: 1
}
})
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(error);
});
}
}
//get:请求方式
// "/api/HPImageArchive.aspx":请求地址,这里的api一定不能忘记,它代表着我们在请求地址前面部分
// params: 我们需要带上的参数就写这个对象中
//.then: 请求成功之后,要执行的代码块
//.catch: 请求失败之后,需要执行的代码块注意事项 在配置好跨域之后,请求的时候,一定不要忘记在前面加上/api如果有修改congfig中的配置,一定记得重启服务,否则你的修改浏览器可能不会给于响应,让你白忙活半天如果自己觉得都没有问题还一直不成功,记得打开network进行查看,不要一味的盯着自己的代码和报错在network中,可以查看自己的请求地址是否有误,需要携带的参数是否有带上,以及参数是否正确

总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
