基于Java服务的前后端分离解决跨域问题

导语:解决跨域问题,前后端都增加相应的允许跨域的代码段即可。

一、后端增加允许跨域的代码,可以在具体controler层加,最好是在filter中添加,这样添加一次就够了,不用在每个controler中都添加了,代码截图如下:

代码如下:

response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
//指定本次预检请求的有效期,单位为秒
response.setHeader("Access-Control-Max-Age", "86400");
//如果存在自定义的header参数,需要在此处添加,逗号分隔
response.setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, " +
"Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token");
//允许跨域请求中携带cookie
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("XDomainRequestAllowed","1");

二、前端增加允许跨域的代码,这里使用的ajax.代码截图如下

 代码如下:

$.ajax({
  url: "http://192.168.10.23:8080/hms/jkpgJkzd.do?action=getMbsdList",
  type: "get",
  crossDomain: true,
  xhrFields: {
    withCredentials: true
  },
  dataType: "json",
  data: {
    "yngrbsh":"31010920090306250337209",
    "pglsh":"157a0a07-73e9-450a-b835-3f396b3b7acb",
    "jbdms":"JB_GXY;JB_NCZ;JB_TNB_YH"
  },
  success: function (data) {
    alert(data);
    alert(JSON.stringify(data));
  }
})

至此完成!!!

转载于:https://www.cnblogs.com/RoyalBlue/p/10451707.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值