Angular.js将基本路径添加到绝对路径URL

时间:2015-03-10 08:30:51

标签: angularjs angularjs-routing angularjs-google-maps

我是angular.js的新手,所以我很抱歉这样一个愚蠢的问题。但也许这会对其他一些乞讨者有所帮助。

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

示例项目包含此$ http.get

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

这适用于基本网址,例如“http://localhost:1234”,但在我的情况下,我得到了

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

因为请求网址是

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

任何人都可以告诉我为什么即使使用绝对路径网址,angular.js还会预先设置基本网址?

谢谢, 汤姆

2 个答案:

答案 0 :(得分: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;
      });
  });

答案 1 :(得分: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;
        }
    };
}]);
相关问题