Angularjs没有'Access-Control-Allow-Origin'

时间:2013-11-29 16:59:45

标签: javascript angularjs cors

无法弄清楚如何解决跨域问题。我的代码:

$apiUrl = 'https://gtmetrix.com/api/0.1/test';
$apiUser = 'joe@vandigroup.com';
$apiKey = '1234567890';
$requestUrl = 'http://converge.io';

    function FetchCtrl($scope, $http, $templateCache) {

        $scope.method = 'post';
        $scope.url = $requestUrl;

        $scope.fetch = function() {
            $scope.code = null;
            $scope.response = null;

            $http({method: $scope.method, url: $apiUrl + '?login-user=' + $apiUser + '&login-pass=34bcb5c46bc6d5fb18a8552820027eb9' + '&url=' + $scope.url, cache: $templateCache}).
            success(function(data, status) {
                $scope.status = status;
                $scope.data = data;
            }).
            error(function(data, status) {
                $scope.data = data || "Request failed";
                $scope.status = status;
            });
        };
        $scope.fetch();

        $scope.updateModel = function(method, url) {
            $scope.method = method;
            $scope.url = url;
        };

    }

错误:

XMLHttpRequest cannot load https://gtmetrix.com/api/0.1/test?login-user=joe@vandigroup.com&login-pass=1234567890&url=http://converge.io. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://converge' is therefore not allowed access. 

似乎我需要包含以下内容但无法使其正常工作:

delete $http.defaults.headers.common['X-Requested-With'];

1 个答案:

答案 0 :(得分:2)

我认为有一个解决方法。这是逻辑

  1. 在您的服务器(或任何服务器端脚本)上制作一个小PHP脚本
  2. 用ajax和你需要的api params调用它(url,user,key ...)
  3. 使用CURL执行请求(或任何等效的)
  4. 打印您需要的内容
  5. 因此,不要使用xhttprequest调用gtmetrix,而是尝试调用您已完成的脚本。