Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prefix $http url

Tags:

angularjs

I can't seem to find an answer to what seems like a reasonable question.

I am using the $http service to call web services for all of my app. All of the server API is hosted at a particular address. Is there any way in which I can get $http to always prefix the provided URL with the API server?

For example, if my API is at http://myAPi/API/, I would like to be able to call:

$http.get("User")...

as opposed to:

$http.get("http://myAPI/API/User")

And Angular prefixes the request with the server address. The aim is to not have the URL spread throughout the app.

Is there a way to achieve this with Angular?

like image 957
jwest Avatar asked Jun 18 '13 10:06

jwest


2 Answers

It's an old question but I made a solution some time ago

angular
  .module('app')
  .config(function ($httpProvider) {
    $httpProvider.interceptors.push(apiInterceptor);
   });

// api url prefix
var API_URL = 'http://localhost:8080/';

function apiInterceptor ($q) {
  return {
    request: function (config) {
      var url = config.url;

      // ignore template requests
      if (url.substr(url.length - 5) == '.html') {
        return config || $q.when(config);
      }

      config.url = API_URL + config.url;
      return config || $q.when(config);
    }
  }
}
like image 115
Jim Vercoelen Avatar answered Nov 01 '22 17:11

Jim Vercoelen


Since $http doesn't have a built-in way of handling this case (other than editing the angular.js source code), you can either wrap your $http in a service:

apiService.get('user'); //where the service defines the $http call and builds the URL

... or simply create an angular constant:

angular.module('myApp', []).constant('apiPrefix', 'http://myAPI/API/')

$http.get(apiPrefix + 'User')

Either way would result to "not have the URL spread throughout the app".

like image 32
Lukus Avatar answered Nov 01 '22 19:11

Lukus