4

我对 angular.js 完全陌生,所以对于这样一个愚蠢的问题,我感到很抱歉。但也许它会对其他初学者有所帮助。

我正在从其他人创建的示例项目中学习,但我使用的是本地 IIS(而不是 IIS Express 或 VS 开发服务器)。所以我的基本路径是http://localhost/SampleProject

示例项目包含此 $http.get

$http.get('https://maps.googleapis.com/maps/api/geocode/json',
            {
                params: params,
                headers: { 'Accept-Language': 'en' }
            }
        )

这适用于“ http://localhost:1234 ”之类的基本 URL ,但在我的情况下,我得到了

Failed to load resource: the server responded with a status of 400 (Bad Request)

因为请求 URL 是

http://localhost/SampleProject/https://maps.googleapis.com/maps/api/geocode/json?sensor=false

谁能告诉我为什么 angular.js 即使使用绝对路径 URL 也要在基本 URL 前添加?

谢谢,汤姆

4

2 回答 2

1

与 $http 无关

从 1.3 开始,Angular 不允许使用全局变量控制器。

这是工作版本: http ://plnkr.co/edit/zGj4Ayy8NIplUva86NP6?p=preview

var app = angular.module('myApp', []);
app.controller('customersController', 
  function($scope,$http) {
    var params = { address: "Zlin, Czech Republic", sensor: false };
    $http.get("https://maps.googleapis.com/maps/api/geocode/json", {
          params: params,
          headers: { 'Accept-Language': 'en' }
      }).success(function(response) {
               $scope.names = response;
      });
  });
于 2015-03-10T13:18:47.433 回答
0

我已经解决了这个问题。这是由错误的默认 URL 处理引起的。我不得不添加

if (config.url.indexOf('http') !== 0 && config.url.indexOf('//' !== 0))

进入 app.js 文件:

app.config(["$httpProvider", function ($httpProvider) {
    $httpProvider.interceptors.push('middleware');
}]);

app.factory('middleware',  ['__baseUrl', 
    function (__baseUrl) {
    return {
        request: function (config) {
            // handle absolute URL request
            if (config.url.indexOf('http') !== 0 && config.url.indexOf('//' !== 0))
            {
               config.url = __baseUrl + config.url
            }
            return config;
        }
    };
}]);
于 2015-04-02T07:01:50.230 回答