Vue中解决跨域问题备忘
1. 什么是跨域?
跨域指浏览器不允许当前页面的所在的源,
去请求另一个源的数据。
源 指的是 协议,端口,域名。
只要这个3个中有一个不同就是跨域。
这里列举一个经典的列子:
http://a.baidu.com访问https://a.baidu.com;
http://a.baidu.com:8080访问http://a.baidu.com:80;
http://a.baidu.com访问http://b.baidu.com;
最根本的解决跨越手段,是后端服务器处理了Cros的跨域问题,
这样前端或程序中可随意访问,无需通过代理转发等手段去解决;
2. Vue中跨域的解决思路: 前端服务[Vue页面]-代理服务[Vue脚手架]-后端服务
3. Vue 中配置跨域,在 vue.config.js中配置
3-1 简单配置:方式一
module.exports = {
devServer: {
proxy: 'http://192.168.100.56:5000'
}
}
3-2 完整配置:方式二
module.exports = {
devServer: {
proxy: {
'/test1': {
target: 'http://192.168.100.88:5000',
pathRewrite: { '^/test1': '' },
ws: true,
changeOrigin: true
},
'/test2': {
target: 'http://192.168.100.99:6000',
pathRewrite: { '^/test2': '' },
ws: true,
changeOrigin: true
}
}
}
}
4. 实例:Vue中使用代理Url–自动发起后端服务请求
import axios from 'axios'
export default {
name: 'Student',
methods: {
注释内容 `:get 请求访问 /test1 前缀开头的地址,实际上访问的地址是: http://192.168.100.88:5000/request_url`
testMethods1() {
axios.get('http://localhost:8080/test1/request_url').then(res => {
console.log(res.data);
});
},
注释内容 :`get 请求访问 /test2 前端开头的地址,实际上访问的地址是:http://192.168.100.99:6000/request_url`
testMethods2() {
axios.get('http://localhost:8080/test2/request_url').then(res => {
console.log(res.data);
})
}
}
}