1.加请求头
后台response添加header,response.setHeader("Access-Control-Allow-Origin", "*");
2.jsonp
前端主要代码(B项目---》请求A项目)
$.ajax({ type : "GET", async : false, url : "http://localhost:8080/getInfoA?username=testB", dataType : "jsonp",//数据类型为jsonp jsonp : "jsonpCallback",//服务端用于接收callback调用的function名的参数 success : function(data) { alert(data.result+data.username); }, error : function() { alert('fail'); } }); |
后台主要代码(A项目)
@RequestMapping("/getInfoA")
@ResponseBody
public String getInfo(HttpServletRequest request, HttpServletResponse response){
String username = request.getParameter("username");
String jsonpCallback = request.getParameter("jsonpCallback");
JSONObject resultJSON = new JSONObject();
try {
resultJSON.put("result", "跨域请求成功");
resultJSON.put("username", username);
} catch (JSONException e) {
e.printStackTrace();
}
return jsonpCallback + "(" + resultJSON.toString() + ")";
}
结果显示
3.nginx或者springcloud 搭建网关
DEMO:https://pan.baidu.com/s/1w73vm9rhqLRFELyiuU9BSg