js跨域问题
当进行前后端分离开发时,可能会预见JS跨域请求的问题
经过查找实践,有如下的四种解决方法:
1、Jsonp
JSONP 是 JSON 的一种使用模式,可以解决主流浏览器的跨域数据访问问题。
实际开发中代码如下:
layui.use(['form','jquery'], function (form,$) {
//监听提交
form.on('submit(login)', function () {
//layer.msg($('#login_form').serialize());
$.post("http://localhost:8080/rbac-rest-service/rbac/account/login",
$('#login_form').serialize(),
function (data) {
//alert(data.code + data.message);
if (data.code == 200) {
layui.data('test',{
key : 'id'
,value : data.data.userid
})
window.location.href = "index.html";
}
},
);
return false;
});
});
2 . SpringMVC的配置文件中加入配置
mvc:cors>
mvc:mapping path="/**" allowed-origins="*" allowed-methods="*"/>
mvc:cors>
这里需要注意的是 allowed-origins="*" 只是允许跨域,但是只支持跨域的方法为get,所以我们需要配置跨域的方法
allowed-methods="*"@CrossOrigin"*", maxAge = 3600)
@RequestMapping(value="/findMune/{id}",method = RequestMethod.GET)
@ApiOperation("查找对应的菜单id")
public Result selectMuneId(@PathVariable Integer id){
return ResultGenerator.genSuccessResult(accountService.selectMenuThingsByUserID(id));
}
4.web-xml中配置过滤器:
参考资料https://segmentfault.com/a/1190000009512081