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

落花浮王杯 提交于 2019-11-30 05:43:51

问题


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?


回答1:


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');


来源:https://stackoverflow.com/questions/31761140/how-to-add-add-request-parameter-to-every-angular-js-http-request-to-start-a-x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!