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?
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.
$http is an AngularJS service for reading data from remote servers.
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.
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 ...
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With