如何向每个 Angular.js $http 请求添加添加请求参数(例如启动 xdebug 会话)

2023-12-07

我的混合应用程序基于 AngularJS 并使用 php REST api。

我想直接从我的 Angular 应用程序调试 php api,而不是使用 REST 控制台或 Postman。它将节省大量时间,特别是对于 POST 和 PUT 请求。

为此,我需要向每个请求添加一个参数,如下所示:

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

我可以配置 $http 来这样做吗?


您可以使用 httpInterceptor (官方 $http文档包含更多信息)

// 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');
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何向每个 Angular.js $http 请求添加添加请求参数(例如启动 xdebug 会话) 的相关文章