前后台分离
前后端分离的项目,前端项目与后端项目部署在两个不同的域下
跨域问题
前端项目,要通过ajax访问后端项目,由于部署在不同的服务器下,出于安全原因,浏览器禁止 Ajax 调用本网站以外的服务器资源
解决
Spring Framework 4.2 GA为跨域问题提供了解决方案,也就是说springMVC的版本要在4.2或以上版本才支持跨域
通过下面注解解决:
@CrossOrigin
允许在 @RequestMapping 注解中指定的所有源和HTTP方法
2个参数:
allowCredentials:是否带上cookie,默认为 false
带上cookie:@CrossOrigin(allowCredentials = "true")。还需要ajax配合,见下面例子origins : 允许可访问的域列表
maxAge:设置 Preflight 请求缓存多长时间(以秒为单位)。
使用
可修饰类、方法
不适用场景(关键)
跨域发请求,分为 简单请求 和 非简单请求,这种方式,仅适用 简单请求,不适用 非简单请求
因为 非简单请求 先发送 OPTIONS 方法的预检请求,详见 链接
例子
简单使用
@RestController
@RequestMapping("rest_index")
@CrossOrigin( allowCredentials = "true")
public class IndexController{
设置参数
@RestController
@RequestMapping("rest_index")
@CrossOrigin(origins = "http://192.168.1.10:8080", maxAge = 3600,allowCredentials = "true")
public class IndexController{
指定该controller中所有方法都能处理来自 http:19.168.1.10:8080 中的请求
ajax例子
jquery
$.ajax({
url:baseUrl+'goods/list',
type:'post',
dataType:'json',//服务器端返回的数据格式是json
xhrFields: { //带上cookie
withCredentials: true
},
data: {
"status":1
},//发给服务器端的数据
success:function(res){ //data:服务器端返回给浏览器端的数据
if(res.code==0){
console.log(res)
}else{
alert(res.msg);
}
},
error:function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest);
alert(textStatus);
alert(errorThrown);
}
});
axios
axios.get(
baseUrl+'goods/list?status=1',
{withCredentials: true}//带cookie
).then(function(res){
console.log(res.data);
})
或者
axios.defaults.withCredentials = true;//带cookie
axios.get(baseUrl+'goods/list?status=1').then(function(res){
console.log(res.data);
})