AngularJS实现跨域请求

来源:互联网 发布:毕福剑酒桌上网络视频 编辑:程序博客网 时间:2024/05/17 07:53
跨域,前端开发中经常遇到的问题,AngularJS实现跨域方式类似于Ajax,使用CORS机制。
下面阐述一下AngularJS中使用$http实现跨域请求数据。

AngularJS XMLHttpRequest:$http用于读取远程服务器的数据
$http.post(url, data, [config]).success(function(){ ... });$http.get(url, [config]).success(function(){ ... });$http.get(url, [config]).success(function(){ ... });

一、$http.jsonp【实现跨域】

1. 指定callback和回调函数名,函数名为JSON_CALLBACK时,会调用success回调函数,JSON_CALLBACK必须全为大写。
2. 指定其它回调函数,但必须是定义在window下的全局函数。url中必须加上callback。

二、$http.get【实现跨域】

1. 在服务器端设置允许在其他域名下访问
response.setHeader("Access-Control-Allow-Origin", "*"); //允许所有域名访问response.setHeader("Access-Control-Allow-Origin", "http://www.123.com"); //允许www.123.com访问
2. AngularJS端使用$http.get()

三、$http.post【实现跨域】

1. 在服务器端设置允许在其他域名下访问,及响应类型、响应头设置
response.setHeader("Access-Control-Allow-Origin", "*");response.setHeader("Access-Control-Allow-Methods","POST");response.setHeader("Access-Control-Allow-Headers","x-requested-with,content-type");
2. AngularJS端使用$http.post(),同时设置请求头信息
$http.post('http://localhost/ajax/getAllIndustryCategoty.pt',{languageColumn:'name_eu'},{'Content-Type':'application/x-www-form-urlencoded'}).success(function(data){$scope.industries = data;});

四、实现方式

跨域方式一【JSONP】:

方法一:
$http.jsonp("http://localhost/sitesettings/getBadgeInfo.pt?jsonp=JSON_CALLBACK&siteid=137bd406").success(function(data){ ... });//  The name of the callback should be the string JSON_CALLBACK.
方法二【返回值,需要使用对应callback方法接收,但如何置于$scope???】:
$http.jsonp("http://localhost/sitesettings/getBadgeInfo.pt?jsonp=badgeabc&siteid=137bd406");function badgeabc(data){ ... }

public String execute() throws Exception {String result = FAIL;response.setHeader("", "");SiteHandlerAction siteHandlerAction = (SiteHandlerAction)BeansFactory.getBean(SiteHandlerAction.class);BadgeHandlerAction badgeHandlerAction = (BadgeHandlerAction)BeansFactory.getBean(BadgeHandlerAction.class);if("".equals(siteid) || siteid == null || StringUtils.isBlank("jsonp")){result = FAIL;}else{Site site = siteHandlerAction.find(siteid);UserBadgeStatus userBadgeStatus = badgeHandlerAction.getUserBadgeStatus(site.getId());if(userBadgeStatus != null){result = "{\"t\":"+userBadgeStatus.getStyle()+",\"l\":"+userBadgeStatus.getSuspend_location()+",\"s\":"+site.getId()+"}";JSONObject jsonObj = JSONObject.fromObject(result);String json = jsonObj.toString();result = jsonp + "(" + json + ")";}}PrintWriter write = response.getWriter();write.print(result);write.flush();write.close();return NONE;}

跨域方式二【$http.get()】:

function getAdustryController($scope,$http){$http.get('http://localhost/ajax/getAllIndustryCategoty.pt?languageColumn=name_eu').success(function(data){$scope.industries = data;});}

跨域方式三【$http.post()】:

function getAdustryController($scope,$http){$http.post('http://localhost/ajax/getAllIndustryCategoty.pt',{languageColumn:'name_eu'},{'Content-Type':'application/x-www-form-urlencoded'}).success(function(data){$scope.industries = data;});}

// java端支持跨域请求public String execute(){response.setHeader("Access-Control-Allow-Origin", "*"); //允许哪些url可以跨域请求到本域response.setHeader("Access-Control-Allow-Methods","POST"); //允许的请求方法,一般是GET,POST,PUT,DELETE,OPTIONSresponse.setHeader("Access-Control-Allow-Headers","x-requested-with,content-type"); //允许哪些请求头可以跨域SiteHandlerAction SiteHandler = (SiteHandlerAction) BeansFactory.getBean(SiteHandlerAction.class);List list = SiteHandler.getAllIndustryCategory(); //所有的分类集合JSONArray jsonArray = JSONArray.fromObject(list); //将list转为jsonString json = jsonArray.toString(); //转为json字符串try {PrintWriter write = response.getWriter();write.print(json);write.close();} catch (IOException e) {e.printStackTrace();}return NONE;}

 

</pre><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; font-family: Arial; font-size: 14px; line-height: 26px;"></p><table style="color: rgb(0, 0, 0); font-size: 14px; clear: right; font-family: simsun; line-height: 25px; margin: 0px auto !important;"><tbody><tr><td style="margin: 0px; padding: 0px;">{{ industry.id }}</td><td style="margin: 0px; padding: 0px;">{{ industry.name_ch }}</td><td style="margin: 0px; padding: 0px;">{{ industry.name_eu }}</td><td style="margin: 0px; padding: 0px;">{{ industry.name_jp }}</td></tr></tbody></table><span style="font-size: 14px; line-height: 26px; font-family: simsun;"><span style="line-height: 25px;"></span></span><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; font-family: Arial; font-size: 14px; line-height: 26px;"></p><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; font-family: Arial; font-size: 14px; line-height: 26px;"><span style="font-family: simsun;"><span style="line-height: 25px;">转载自:http://www.bkjia.com/<a target=_blank href="http://lib.csdn.net/base/18" class="replace_word" title="JavaScript知识库" target="_blank" style="color: rgb(223, 52, 52); text-decoration: none; font-weight: bold;">JavaScript</a>/977935.html</span></span></p><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; font-family: Arial; font-size: 14px; line-height: 26px;"></p><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; font-family: Arial; font-size: 14px; line-height: 26px;"></p><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; font-family: Arial; font-size: 14px; line-height: 26px;"></p><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; font-family: Arial; font-size: 14px; line-height: 26px;"></p><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; font-family: Arial; font-size: 14px; line-height: 26px;"></p><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; font-size: 14px; font-family: 'Microsoft YaHei'; color: rgb(63, 63, 63); line-height: 30px;"><span style="padding: 0px; font-size: 16px;">大家会自然想到只有一个字母之差的JSON吧~</span></p><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; font-size: 14px; font-family: 'Microsoft YaHei'; color: rgb(63, 63, 63); line-height: 30px;"><span style="padding: 0px; font-size: 16px;">JSON(JavaScript Object Notation)和JSONP(JSON with Padding)虽然只有一个字母的差别,但其实他们根本不是一回事儿</span></p><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; font-size: 14px; font-family: 'Microsoft YaHei'; color: rgb(63, 63, 63); line-height: 30px;"><span style="padding: 0px; font-size: 16px;">JSON是一种数据交换格式,而JSONP是一种依靠开发人员的聪明才智创造出的一种非官方跨域数据交互协议。我们拿最近比较火的谍战片来打个比方,JSON是地下党们用来书写和交换情报的“暗号”,而JSONP则是把用暗号书写的情报传递给自己同志时使用的接头方式。看到没?一个是描述信息的格式,一个是信息传递双方约定的方法。</span></p><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; font-size: 14px; font-family: 'Microsoft YaHei'; color: rgb(63, 63, 63); line-height: 30px;"> </p><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; font-size: 14px; font-family: 'Microsoft YaHei'; color: rgb(63, 63, 63); line-height: 30px;"><span style="padding: 0px; font-size: 16px;">浏览器是存在<a target=_blank target="_blank" href="https://developer.mozilla.org/zh-CN/docs/Web/Security/Same-origin_policy" style="color: rgb(51, 51, 51); text-decoration: none; padding: 0px;">同源策略</a>这个机制的,在全局层面禁止了页面加载或执行与自身来源不同的域的任何脚本。</span></p><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; font-size: 14px; font-family: 'Microsoft YaHei'; color: rgb(63, 63, 63); line-height: 30px;"><span style="padding: 0px; font-size: 16px;">JSONP是一种可以绕过浏览器的安全限制,从不同的域请求数据的方法。</span></p><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; font-size: 14px; font-family: 'Microsoft YaHei'; color: rgb(63, 63, 63); line-height: 30px;"> </p><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; font-size: 14px; font-family: 'Microsoft YaHei'; color: rgb(63, 63, 63); line-height: 30px;"><span style="padding: 0px; font-size: 16px;">Web页面上调用js文件时则不受是否跨域的影响(不仅如此,我们还发现凡是拥有”src”这个属性的标签都拥有跨域的能力,比如<script>、<img>、<iframe>);</span></p><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; font-size: 14px; font-family: 'Microsoft YaHei'; color: rgb(63, 63, 63); line-height: 30px;"><span style="padding: 0px; font-size: 16px;">如果想通过纯web端(ActiveX控件、服务端代理、属于未来的HTML5之Websocket等方式不算)跨域访问数据就只有一种可能,那就是在远程服务器上设法把数据装进js格式的文件里,供客户端调用和进一步处理;JSON的纯字符数据格式可以简洁的描述复杂数据,被js原生支持,所以在<span style="padding: 0px; line-height: 1.5;">web客户端通过与调用脚本一模一样的方式,来调用跨域服务器上动态生成的js格式文件(一般以JSON为后缀),显而易见,服务器之所以要动态生成JSON文件,目的就在于把客户端需要的数据装入进去。</span><span style="padding: 0px; line-height: 1.5;">为了便于客户端使用数据,逐渐形成了一种非正式传输协议,人们把它称作JSONP,该协议的一个要点就是允许用户传递一个callback参数给服务端,然后服务端返回数据时会将这个callback参数作为函数名来包裹住JSON数据,这样客户端就可以随意定制自己的函数来自动处理返回数据了。</span></span></p><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; font-size: 14px; font-family: 'Microsoft YaHei'; color: rgb(63, 63, 63); line-height: 30px;"> </p><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; font-size: 14px; font-family: 'Microsoft YaHei'; color: rgb(63, 63, 63); line-height: 30px;"><span style="padding: 0px; font-size: 16px;">JSONP的原理是通过<script>标签发起一个GET请求来取代XHR请求。JSONP生成一个<script>标签并插到DOM中,然后浏览器会接管并向src属性所指向的地址发送请求。</span></p><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; font-size: 14px; font-family: 'Microsoft YaHei'; color: rgb(63, 63, 63); line-height: 30px;"><span style="padding: 0px; font-size: 16px;">当服务器返回请求时,响应结果会被包装成一个JavaScript函数,并由该请求所对应的回调函数调用。</span></p><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; font-size: 14px; font-family: 'Microsoft YaHei'; color: rgb(63, 63, 63); line-height: 30px;"><span style="padding: 0px; font-size: 16px;"><a target=_blank href="http://lib.csdn.net/base/23" class="replace_word" title="AngularJS知识库" target="_blank" style="color: rgb(223, 52, 52); text-decoration: none; font-weight: bold;">AngularJS</a>在$http服务中提供了一个JSONP辅助函数。通过$http服务的jsonp方法可以发送请求,如下所示:</span></p><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; font-size: 14px; font-family: 'Microsoft YaHei'; color: rgb(63, 63, 63); line-height: 30px;"><span style="padding: 0px; font-size: 16px;">     $http .jsonp("https://api.github.com?callback=JSON_CALLBACK") .success(function(data) { </span></p><p style="margin-top: 0px; margin-bottom: 0px; margin-left: 30px; padding-top: 0px; padding-bottom: 0px; font-size: 14px; font-family: 'Microsoft YaHei'; color: rgb(63, 63, 63); line-height: 30px;"><span style="padding: 0px; font-size: 16px;">  // 数据<br style="padding: 0px;" />});</span></p><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; font-size: 14px; font-family: 'Microsoft YaHei'; color: rgb(63, 63, 63); line-height: 30px;"><span style="padding: 0px; font-size: 16px;">当请求被发送时,AngularJS会在DOM中生成一个如下所示的<script>标签:</span></p><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; font-size: 14px; font-family: 'Microsoft YaHei'; color: rgb(63, 63, 63); line-height: 30px;"><span style="padding: 0px; font-size: 16px;">  <script src="https://api.github.com?callback=angular.callbacks._0" type="text/javascript"></script> </span></p><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; font-size: 14px; font-family: 'Microsoft YaHei'; color: rgb(63, 63, 63); line-height: 30px;"><span style="padding: 0px; font-size: 16px;">注意,JSON_CALLBACK被替换成了一个特地为此请求生成的自定义函数。当支持JSOPN的服务器返回数据时,数据会被包装在由AngularJS生成的具名函数angular.callbacks._0中在这个例子中,GitHub服务器会返回包含在回调函数中的JSON数据,响应看起来如下所示: </span></p><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; font-size: 14px; font-family: 'Microsoft YaHei'; color: rgb(63, 63, 63); line-height: 30px;"><span style="padding: 0px; font-size: 16px;"> // 简写  </span></p><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; font-size: 14px; font-family: 'Microsoft YaHei'; color: rgb(63, 63, 63); line-height: 30px;"><span style="padding: 0px; font-size: 16px;">  angular.callbacks._0({ </span></p><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; font-size: 14px; font-family: 'Microsoft YaHei'; color: rgb(63, 63, 63); line-height: 30px;"><span style="padding: 0px; font-size: 16px;">    ‘meta‘: { </span><br style="padding: 0px;" /><span style="padding: 0px; font-size: 16px;">      ‘X-RateLimit-Limit‘: ‘60‘, </span><br style="padding: 0px;" /><span style="padding: 0px; font-size: 16px;">      ‘status‘: 200 </span><br style="padding: 0px;" /><span style="padding: 0px; font-size: 16px;">    }, </span><br style="padding: 0px;" /><span style="padding: 0px; font-size: 16px;">    ‘data‘: { </span><br style="padding: 0px;" /><span style="padding: 0px; font-size: 16px;">      ‘current_user_url‘: ‘https://api.github.com/user‘ </span><br style="padding: 0px;" /><span style="padding: 0px; font-size: 16px;">    } </span><br style="padding: 0px;" /><span style="padding: 0px; font-size: 16px;">  }) </span><br style="padding: 0px;" /><span style="padding: 0px; font-size: 16px;">当AngularJS调用指定的回调函数时会对$http的promise对象进行resolve。当我们自己开发支持JSONP的后端服务时,要确保响应的数据被包含在请求所指定的回调函数中。使用JSONP需要意识到潜在的安全风险。首先,服务器会完全开放,允许后端服务调用应用中的任何JavaScript。不受我们控制的外部站点(或者蓄意攻击者)可以随时更改脚本,使我们的整个站点变得脆弱。服务器或中间人有可能会将额外的JavaScript逻辑返回给页面,从而将用户的隐私数据暴露出来。由于请求是由<script>标签发送的,所以只能通过JSONP发送GET请求。并且脚本的异常也很难处理。使用JSONP一定要谨慎,同时只跟信任并可以控制的服务器进行通信。</span></p><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; font-size: 14px; font-family: 'Microsoft YaHei'; color: rgb(63, 63, 63); line-height: 30px;"> </p><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; font-size: 14px; font-family: 'Microsoft YaHei'; color: rgb(63, 63, 63); line-height: 30px;"><span style="padding: 0px; font-size: 16px;">一句话就是利用script标签绕过同源策略,获得一个类似这样的数据,jsonpcallback是页面存在的回调方法,参数就是想得到的json。</span></p><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; font-size: 14px; font-family: 'Microsoft YaHei'; color: rgb(63, 63, 63); line-height: 30px;"> </p><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; font-size: 14px; font-family: 'Microsoft YaHei'; color: rgb(63, 63, 63); line-height: 30px;"> </p><div style="font-size: 14px; font-family: 'Microsoft YaHei'; padding: 0px; color: rgb(63, 63, 63); line-height: 30px;"><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px;"><span style="padding: 0px; font-size: 16px;"><span style="padding: 0px;"><span style="padding: 0px; color: rgb(255, 0, 0);"><a target=_blank href="http://lib.csdn.net/base/22" class="replace_word" title="jQuery知识库" target="_blank" style="color: rgb(223, 52, 52); text-decoration: none; font-weight: bold;">jQuery</a>中jsonp的使用</span></span></span></p></div><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; font-size: 14px; font-family: 'Microsoft YaHei'; color: rgb(63, 63, 63); line-height: 30px;"> </p><div style="font-size: 14px; font-family: 'Microsoft YaHei'; padding: 0px; color: rgb(63, 63, 63); line-height: 30px;"><div class="cnblogs_code" style="padding: 0px;"><pre style="white-space: pre-wrap; word-wrap: break-word; font-family: 'Microsoft YaHei'; padding: 0px;"><span style="padding: 0px; color: rgb(0, 0, 0); font-size: 16px;">myUrl = "http://localhost:8090/api/test";$.ajax({  type:"GET",  url:myUrl,  dataType:"jsonp",  jsonp:"callback",  jsonpCallback:"jsonpCallback",  success:function(data){    alert(data.msg);<br style="padding: 0px;" />  }});function jsonpCallback(data){  alert(data);}<br style="padding: 0px;" /></span>
1.jsonp只能使用get请求,解决同源问题,返回javascript代码,因为请求javascript文件是没有同源问题的。
2.当请求数据类型为jsonp时,会将callback=jsonpCallback加在url上,http://localhost:8090/api/testcallback=jsonpCallback
3.前台javascript中定义jsonpCallback函数,此函数必须定义在window下,也就是全局的函数,否则找不到。
4.后台获取请求的callback参数值jsonpCallback,返回字符串"jsonpCallback(result)",result为返回结果。
5.请求返回的是script tag,首先会调用jsonpCallback函数,不管是否找到该函数,都会调用success函数。
6.如果没有定义jsonp和jsonpCallback,jsonp默认为"callback",jsonpCallback会是Jquery自动生成的函数名。

 

angularJS中jsonp的使用

myUrl = "http://localhost:8090/api/testcallback=JSON_CALLBACK";$http.jsonp(myUrl).success(
  function(data){    alert(data);  });1.angularJS中使用$http.jsonp函数2.指定callback和回调函数名,函数名为JSON_CALLBACK时,会调用success回调函数,JSON_CALLBACK必须全为大写。3.也可以指定其它回调函数,但必须是定义在window下的全局函数。4.url中必须加上callback5.当callback为JSON_CALLBACK时,只会调用success,即使window中有JSON_CALLBACK函数,也不会调用该函数。
0 0
原创粉丝点击