<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type : "GET",
async : false,
url : "http://127.0.0.1:8081/ajaxJsonpB",
dataType : "jsonp",
jsonp : "jsonpCallback",//服务端用于接收callback调用的function名的参数
success : function(data) {
alert(data["errorCode"]);
},
error : function() {
alert('fail');
}
});
});
</script>
@RequestMapping(value = "/ajaxJsonpB", method = RequestMethod.GET)
public void ajaxB(HttpServletResponse response, String jsonpCallback) throws IOException {
JSONObject root = new JSONObject();
root.put("errorCode", "200");
root.put("errorMsg", "登陆成功");
response.setHeader("Content-type", "text/html;charset=UTF-8");
PrintWriter writer = response.getWriter();
writer.print(jsonpCallback + "(" + root.toString() + ")");
writer.close();
}
缺点:不支持post请求,代码书写比较复杂
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type : "GET",
async : false,
url : "http://127.0.0.1:8081/ajaxB",
dataType : "json",
success : function(data) {
alert(data["errorCode"]);
},
error : function() {
alert('fail');
}
});
});
</script>
@RequestMapping("/ajaxB")
public Map<String, Object> ajaxB(HttpServletResponse response) {
//告诉浏览器可以跨域 * 代表所有域名都可以跨域 正常将这个代码应该放在过滤器中
response.setHeader("Access-Control-Allow-Origin", "*");
Map<String, Object> result = new HashMap<String, Object>();
result.put("errorCode", "200");
result.put("errorMsg", "登陆成功");
return result;
}
设置响应头允许跨域,如果在实际项目中,该代码建议放在过滤器中。
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type : "POST",
async : false,
url : "http://127.0.0.1:8080/forwardB",
dataType : "json",
success : function(data) {
alert(data["errorCode"]);
},
error : function() {
alert('fail');
}
});
});
</script>
// A项目进行转发到B项目
@RequestMapping("/forwardB")
@ResponseBody
public JSONObject forwardB() {
JSONObject result = HttpClientUtils.httpGet("http://127.0.0.1:8081/ajaxB");
System.out.println("result:" + result);
return result;
}
// B项目代码
@RequestMapping("/ajaxB")
public Map<String, Object> ajaxB(HttpServletResponse response) {
Map<String, Object> result = new HashMap<String, Object>();
result.put("errorCode", "200");
result.put("errorMsg", "登陆成功");
return result;
}
server {
listen 80;
server_name 127.0.0.1;
#A项目
location /a {
proxy_pass http://127.0.0.1:8080/;
index index.html index.htm;
}
#B项目
location /b {
proxy_pass http://127.0.0.1:8081/;
index index.html index.htm;
}
}
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type : "POST",
async : false,
url : "http://127.0.0.1/b/ajaxB",
dataType : "json",
success : function(data) {
alert(data["errorCode"]);
},
error : function() {
alert('fail');
}
});
});
</script>
@RequestMapping("/ajaxB")
public Map<String, Object> ajaxB(HttpServletResponse response) {
Map<String, Object> result = new HashMap<String, Object>();
result.put("errorCode", "200");
result.put("errorMsg", "登陆成功");
return result;
}
使用SpringCloud Zuul搭建API接口网关
原文:https://www.cnblogs.com/haoworld/p/distributed-wang-zhan-kua-yu-jie-jue-fang-an.html