Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS globally modify the URL of every request in $http

Tags:

Let's set up a simple example:

$scope.whatDoesTheFoxSay = function(){     $http.post("/backend/ancientMystery", { ... 

How can I globally transform the URL where the post request is sent to? Essentially I want to prepend an URL to every http request.

What I have tried is setting a variable in the $rootScope containing the url when the application starts. But this is not what I want my code to look like:

$scope.whatDoesTheFoxSay = function(){     $http.post($rootScope.backendUrl + "/backend/hidingDeepInTheWoods", { ... 

Am I correct assuming that I should look into $httpProvider.defaults.transformRequest? Can anyone provide me with some basic example code?

like image 621
subZero Avatar asked Sep 24 '13 14:09

subZero


People also ask

How do you modify the $HTTP request default Behaviour?

To add or overwrite these defaults, simply add or remove a property from these configuration objects. To add headers for an HTTP method other than POST or PUT, simply add a new object with the lowercased HTTP method name as the key, e.g. $httpProvider. defaults.

What is $HTTP in AngularJS?

$http is an AngularJS service for reading data from remote servers.

Is http request is synchronous or asynchronous in AngularJS?

The problem is as follows, $http. get is asynchronous, before the response is fetched, the function returns. Therefore the calling function gets the data as empty string.

What is the use of interceptor in AngularJS?

HTTP Interceptors are used for adding custom logic for authentication, authorization, session/state management, logging, modifying Response, URL rewriting, Error handling, Caching, adding custom header, timestamp in the request /response, encrypt and decrypt the request and response information or manipulate the ...


1 Answers

I have another approach of using request interceptor with $http which will handle all the url's at one common place

<!doctype html> <html ng-app="test">   <head>     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.2/angular.js"></script>    </head>  <body ng-controller="test" >       <!-- tabs -->    <script>      var app = angular.module('test', []);      app.config(function ($httpProvider) {          $httpProvider.interceptors.push(function ($q) {              return {                  'request': function (config) {                      config.url = config.url + '?id=123';                      return config || $q.when(config);                   }               }          });      });       app.controller('test', function ($scope,$http) {          $http.get('Response.txt').success(function (data) { alert(data) }).error(function (fail) {           });      });     </script> </body>   </html> 
like image 126
Ajay Beniwal Avatar answered Oct 23 '22 09:10

Ajay Beniwal