简体   繁体   中英

How to add add request parameter to every Angular.js $http request (to start a xdebug session for example)

My hybrid application is based on AngularJS and uses a php REST api.

I would like to debug the php api directly from my Angular app instead to use REST console or Postman. It would save a lot of time especially for POST and PUT requests.

In order to do so I would need to add a parameter to each request like so:

http://localhost:8000/api/contacts?XDEBUG_SESSION_START=PHPSTORM

Can I config $http to do so?

You can use httpInterceptor for that (official $http documentation contains more info)

// register the interceptor as a service
$provide.factory('xdebugInterceptor', function($q) {
  return {
    // optional method
    'request': function(config) {
      // do something on success

      // !!! adjust the config object
      // add request param XDEBUG_SESSION_START=PHPSTORM
      // it will be added to every made request

      config.params = config.params || {};
      config.params.XDEBUG_SESSION_START: "PHPSTORM";

      return config;
    },

    // optional method
   'requestError': function(rejection) {
      // do something on error
      return $q.reject(rejection);
    },


    // optional method
    'response': function(response) {
      // do something on success
      return response;
    },

    // optional method
   'responseError': function(rejection) {
      // do something on error
      return $q.reject(rejection);
    }
  };
});

// make this conditional so you use it only in DEV mode
$httpProvider.interceptors.push('xdebugInterceptor');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM