ionic/angular 跨域问题

来源:互联网 发布:日本讨厌韩国知乎 编辑:程序博客网 时间:2024/06/06 00:19

angular 为了解决跨域问题 一些第三方接口会提供jsonp来调用,需要使用callback=JSON_CALLBACK来处理 

  这个时候问题来了,有些借口是不支持callback里面带有点语法的,最典型的就是豆瓣了,而callback=JSON_CALLBACK 会被 angular转换成 callback = angular.callbacks._[id]这种形式,

  这个时候就会报错了,因为返回的是json格式而不是jsonp格式。为了解决这类问题最简单的方法肯定是重定义方法名,我在这里就是采用这种方法的,但是我们应该怎么改名字呢?答案就是在http拦截器里面,详情看代码。 

https://api.douban.com/v2/book/isbn/' + isbn + "/reviews?callback=JSON_CALLBACK"

.factory("httpInterceptor", ["App", "$rootScope", '$injector','$timeout', function (App, $rootScope, $injector,$timeout) {return {            request: function (config) {                if (config.method === 'JSONP') {                    console.log(config);                    var callbackId = angular.callbacks.counter.toString(36);                    config.callbackName = 'angular_callbacks_' + callbackId;                    config.url = config.url.replace('JSON_CALLBACK', config.callbackName);                    $timeout(function () {                        window[config.callbackName] = angular.callbacks['_' + callbackId];                    }, 0, false);                }                if (!config.isLoading) {                    count++;                    $rootScope.$broadcast('loading:show')                }                return config || App.q.when(config);            },            requestError: function (rejection) {               return App.q.reject(rejection)            },            response: function (response) {               return response || App.q.when(response);            },            responseError: function (rejection) {// do something on response error                return App.q.reject(rejection);            }        }    }])
以上思路来源于 http://stackoverflow.com/questions/25400891/how-to-custom-set-angularjs-jsonp-callback-name

.factory('jsonpInterceptor', function($timeout, $window, $q) {  return {    'request': function(config) {      if (config.method === 'JSONP') {        var callbackId = angular.callbacks.counter.toString(36);        config.callbackName = 'angular_callbacks_' + callbackId;        config.url = config.url.replace('JSON_CALLBACK', config.callbackName);        $timeout(function() {          $window[config.callbackName] = angular.callbacks['_' + callbackId];        }, 0, false);      }      return config;    },    'response': function(response) {      var config = response.config;      if (config.method === 'JSONP') {        delete $window[config.callbackName]; // cleanup      }      return response;    },    'responseError': function(rejection) {      var config = rejection.config;      if (config.method === 'JSONP') {        delete $window[config.callbackName]; // cleanup      }      return $q.reject(rejection);    }  };})

0 0