跨域问题是浏览器的一种保护机制,要求协议,域名,端口号都相同,才可以安全访问。
如:http://www.abc.com/a 和 http://www.abc.com/b。都是http协议,域名都是www.abc.com,端口号都是默认的80,a,b是域名下的不同文件,可以直接请求。
这里我写一个小demo
前端,向本机的后端发送一个请求(原生js)
url: http://127.0.0.1:63176/test.html
window.onload = function (){
let xhr = new XMLHttpRequest();
xhr.open('get','http://127.0.0.1:8080/hello');
xhr.send();
xhr.onreadystatechange = function (){
if(xhr.status >= 200 && xhr.status < 300)
console.log(xhr.responseText)
else
console.log('Error')
}
}
后端,返回字符串hello(java)
接口:http://127.0.0.1:8080/hello
@RequestMapping("hello")
public String sayHello(){
return "hello";
}
这个时候是会报错的,因为前端网页url是 http://127.0.0.1:63176/test.html,后端接口是http://127.0.0.1:8080/hello,虽然协议和域名相同,但是端口号不同,出现跨域问题。
img,link,script 三个标签是可以跨域请求的,不受同源的限制。所以动态引入 script 标签,可以解决前端的跨域问题。
前端:
<script>
function get(data){
console.log(data)
}
</script>
<script>
window.onload = function() {
var oBtn = document.getElementById('btn');
oBtn.onclick = function() {
var script = document.createElement("script");
script.src = "http://127.0.0.1:8080/hello?callback=get";
document.head.append(script);
}
}
</script>
只能使用与get请求,且callback是回调函数
后端:
@RequestMapping("hello")
public String sayHello(){
User user = new User();
user.setAge(18);
user.setName("lala");
return "get(\""+user.toString()+"\")";
}
在vue.config.js文件中配置代理服务器
//代理服务器
devServer: {
host: 'localhost',
port: 8081,
proxy: {
//代理以/hello开头的接口
'/hello': {
target: 'http://localhost:8080',// 要跨域的域名
changeOrigin: true, // 是否开启跨域
}
}
}
从 localhost:8081 到 localhost:8080,浏览器请求 localhost:8080 和前端网页是同源的,不会出现跨域现象,而请求localhost:8080 这个地址不是由浏览器完成,自然就不会出现跨域问题。
前端:
created(){
this.$axios.get('/hello/hi')
.catch(e => {
console.log(e)
})
},
后端:
@RequestMapping("hello/hi")
public String sayHi(){
return "hi";
}