博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
AngularJS的$http的跨域问题
阅读量:4674 次
发布时间:2019-06-09

本文共 1614 字,大约阅读时间需要 5 分钟。

了解了angularjs的$http方法的本质跟jquery ajax方法是一样的,就开始担心跨域的问题,以前开发工作紧张,遇到了也把跨域问题放下,毕竟做的传统web开发,后端提供的接口和前端都会发布在一个服务器上,现在做的项目大了,自然遇到一些团队只负责发布API,而我们团队只能去调用,跨域肯定是不可跳过的步骤啦。

没想到这么一了解居然有这么多跨域的方法,也不知道可行不可行!先当时mark了吧

 

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

1. 指定callback和回调函数名,函数名为JSON_CALLBACK时,会调用success回调函数,JSON_CALLBACK必须全为大写。

2. 指定其它回调函数,但必须是定义在window下的全局函数。url中必须加上callback。

实现:

方法一:

$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){ ... }

二、$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.get('http://localhost/ajax/getAllIndustryCategoty.pt?languageColumn=name_eu').success(function(data){	$scope.industries = data;});

三、$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;});
 

转载于:https://www.cnblogs.com/flyGrey/p/6294091.html

你可能感兴趣的文章