Nginx代理
这种方式比较简单,将A应用和B应用都通过一个统一的地址进行转发,这样就可以避免跨域问题出现。
通过nginx转发后,所有的域都映射到www.gameloft9.top了,然后通过/manager,/service分别转发到各自的应用中,巧妙的避免了跨域问题。如果是纯前端项目,可以直接托管到nginx里面,也可以解决跨域问题,原理一样。
JSONP
/**
* 测试JSONP跨域请求
* */
function testJsonP() {
$.ajax({
url: root + "/testjsonp.do",
type: "GET",//jsonp只支持GET请求
data: request,
dataType: "jsonp",
jsonp: "callback",//指定查询字符串中回调方法key
jsonpCallback: "print",//指定查询字符串中回调方法value,例如callback=print
success: function (data) {//返回的是回调方法的入参
//alert(data)
}
})
}
设置Access-Control-Allow-*头
/**
* 测试ajax 设置head跨域请求
* */
@RequestMapping(value = "/testCrossOrigin.do", method = RequestMethod.POST)
@ResponseBody
public String crossOrigin(Model model,String number,HttpServletRequest request,HttpServletResponse response)throws Exception{
//设置response header,允许跨域请求
response.setHeader("Access-Control-Allow-Origin","*");
response.setHeader("Access-Control-Allow-Methods","POST");
response.setHeader("Access-Control-Allow-Headers","x-requested-with,content-type");
response.setHeader("Access-Control-Allow-Max-Age","1728000");//单位:秒,这里是20天
Integer result = Integer.parseInt(number);
result = result*result;
return result.toString();
}