为什么用vue-cli创建之后的项目调用后台接口会出现跨域的问题。直接调去后台接口就会出现404。是因为vue的localhost与访问域名不一致,导致的跨域问题。
所以在这里就用到了代理,也就是代理服务器-Proxy Server,也就是网络信息的中转站。
设置代理:
在config/index.js中,找到dev:{}, 在这里面设置一个proxyTable
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/api': {
target: 'http://localhost:9090/', // 设置你调用的接口域名和端口号,如果协议是https 的,还需要加一个参数,secure:false;
changeOrigin: true, // 跨域
pathRewrite: {
'^/api': ''//这里就是用api替换我们的target,后面组件中调用接口直接可以用api来替换。
}
}
}
},ok ,这个时候我们请求接口就不存在跨域问题了。
⚠️:原接口是http://localhost:8080/niahao;
页面访问的接口是:http://localhost:8080/api/niahao;
这里是正确的。
未完待续……