在前端跨域时,出现跨域访问接口是经常的事,我在做angular访问时,现在试验过的跨域方法有两种:jsonp和nginx反向代理。

其中的jsonp 比较简便一点:

关于做反向代理问题

data.js

关于做反向代理问题

但是在处理post请求时,这种方法显然不太合适。此时nginx跨域方案算的上是一种比较优质的方案。

1.anginx.conf配置文件在http 下面的server中,添加代理项:

关于做反向代理问题

前端代码中的请求也需要修改:

HTML:

<div id="hot" class="swiper-container hot" ng-app ="mhotVideo" ng-controller = "hotVideosctrl">
<ul class="swiper-wrapper">
<li class="swiper-slide" ng-repeat = "hotvideo in hotvideos track by $index">
<div class = "hotimg"><img src="{{hotvideo.wiki.screens[0].url}}" alt=""></div>
<div class = "hottip"></div>
<div class = "hottitle">{{hotvideo.wiki.title}}</div>
</li>

</ul>
</div>

JS:

var hotvideos = angular.module("mhotVideo",[]);
/*
hotvideos.config(function ($httpProvider){
      $httpProvider.defaults.transformRequest=function (obj){
       $.param(obj);
      };


        $httpProvider.defaults.headers.post['Content-Type']='application/x-www-form-urlencoded';
    });
    */
hotvideos.controller("hotVideosctrl",function($scope,$http){
var mjson = {"action": "GetWikiInfoByTagOrChildTag",
            "device": {
                "dnum": "123"
            },
            "user": {
                "userid": "123"
            },
            "param": {
                "child_tag":"动作",
                "country":"",
                "tag":"电影",
                "page": 1,
                "pagesize":10
            }
    };
//$scope.mpost = function(){
// console.log("post请求发起");
$http({
method:'post',
//url:"http://XX.XX.XX.XX:XXXX/Epg",
url:"/Epg",
data:mjson,
}).then(function(data){
console.log("请求发送成功");
$scope.hotvideos = data.data.wikis;
console.log($scope.hotvideos);
}).catch(function(){
alert("数据呢?");
});
//} ;
});
angular.bootstrap(document.getElementById("hot"), ['mhotVideo']);

相关文章:

  • 2021-10-15
  • 2022-12-23
  • 2022-01-20
  • 2022-12-23
  • 2022-12-23
  • 2021-12-07
  • 2021-12-14
猜你喜欢
  • 2021-10-10
  • 2022-12-23
  • 2022-01-07
  • 2022-12-23
  • 2022-02-08
相关资源
相似解决方案