什么叫跨域呢。比如a.a.com/a.jsp 这里有个jsp访问b.b.com/b.servlet,a通过ajax访问b数据能传输,也能获取,但是异步回调时不会执行,会出现如下报错,这就是跨域导致的回调失效。
![](http://upload-images.jianshu.io/upload_images/5548226-23085c36a77a9867.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/401)
image.png
XMLHttpRequest cannot load http://a.a.com/A/UserFromServlet.No Access-Control-Allow-Origin header is present on the requested resource.Origin http://b.b.com is therefore not allowed access.
跨域问题解决方案大致有4种
1.在响应头中设置运行跨域---这简单的 小企业用的多 接口这里加入 resp.setHeader("Access-Control-Allow-Origin","*"); ☆☆☆☆☆
![](http://upload-images.jianshu.io/upload_images/5548226-b72d675660439745.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/700)
image.png
2.jsonp 但是jsonp有缺点,只能发送get请求,即使ajax使用post请求也会自动转换成get请求 限制比较大,用的少,而且前端后台都要改,感觉不实用 ×××××
前端操作
![](http://upload-images.jianshu.io/upload_images/5548226-e49a150813b30363.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/700)
image.png
后台的代码,后台这里也应该使用doGet。
![](http://upload-images.jianshu.io/upload_images/5548226-f1069e12b74f66c3.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/700)
image.png
3.搭建网关系统,其实就是用nginx做代理解决跨域问题,可以参考
nginx配置和安装 中第七点 建议使用 ☆☆☆☆☆
4.使用后台服务转发(通过后台httpclient访问另外个后台接口拿到数据在传到前端) 不推荐使用,等于调用2次接口,性能消耗很多 ×××××
原文链接:http://www.jianshu.com/p/da1d4dcfbd8c
关注我的公众号,都是满满的干货!
![](https://images2017.cnblogs.com/blog/1216628/201712/1216628-20171230092721554-2013271538.gif)