4

I'm absolutely new to angular.js, so I'm sorry for a such stupid question. But maybe it would help a little bit to other beginers.

I'm learning from a sample project created by someone else, but I'm using a local IIS (instead of IIS Express or VS dev. server). So my base path is http://localhost/SampleProject

The sample project contains this $http.get

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

This works on base URL like "http://localhost:1234", but in my case I get

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

because request URL is

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

Can anyone tell me why is angular.js prepending base url even if absolute path URL is used?

Thanks, Tom

Tomino
  • 5,969
  • 6
  • 38
  • 50

2 Answers2

1

Nothing related to $http

From 1.3, Angular does not allow global variable controller.

Here is the working version: 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;
      });
  });
allenhwkim
  • 27,270
  • 18
  • 89
  • 122
0

I've solved this issue. It was caused by wrong default URL handling. I had to add

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

line into app.js file:

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;
        }
    };
}]);
Tomino
  • 5,969
  • 6
  • 38
  • 50