【问题标题】:How to get all Apigee request headers in JavaScript?如何在 JavaScript 中获取所有 Apigee 请求标头?
【发布时间】:2014-05-02 13:29:38
【问题描述】:

我有一些 JavaScript,需要在其中处理 Apigee 中的所有请求标头。在线文档 (http://apigee.com/docs/api-services/content/javascript-object-model) 提到它们可以通过 context.proxyRequest.headers 作为名称/值对使用。我是否必须遍历它们,或者它们是否可以通过 context.proxyRequest.headers 以数组的形式整体提供?

谢谢。

【问题讨论】:

    标签: javascript http-headers apigee


    【解决方案1】:

    您可以使用以下内容通过您的 javascript 访问请求标头

    var request_headers = context.getVariable("request.headers.names");
    

    此变量的作用域仅在代理请求流内。

    【讨论】:

    • 类似地,您可以使用“request.header.{header_name}.values”获取每个标头的值。您不必遍历它们。
    【解决方案2】:

    此代码适用于我检查所有请求标头:

    // reflectHeaders.js
    // ------------------------------------------------------------------
    //
    // formats the request headers into a JSON response.
    //
    // created: Tue May 13 11:42:19 2014
    // last saved: <2014-May-13 12:05:39>
    
    var requestHeaders = context.getVariable("request.headers.names"),
        result = {};
    
    // requestHeaders is a java.util.TreeMap$KeySet; convert it to string
    requestHeaders = requestHeaders + '';
    
    // convert from "[A, B, C]" to an array of strings: ["A", "B", "C"]
    requestHeaders = requestHeaders.slice(1, -1).split(', ');
    
    // insert each header into the response
    requestHeaders.forEach(function(x){
      var a = context.getVariable("request.header." + x );
      result[x] = a;
    });
    
    // set the response content:
    context.setVariable('response.content', JSON.stringify(result, null, 2));
    

    如果你喜欢,here is a complete proxy bundle 会展示如何使用这个 JS。只需将其部署到 Apigee 组织中并像这样调用它:

    curl -H x-custom-header:my-custom-value http://ORG-ENV.apigee.net/v1/ex-js-header
    

    输出:

    {
      "Accept": "*/*",
      "Host": "ORG-ENV.apigee.net",
      "User-Agent": "curl/7.30.0",
      "x-custom-header": "my-custom-value"
    }
    

    【讨论】:

      猜你喜欢
      • 2013-10-25
      • 2011-04-22
      • 1970-01-01
      • 1970-01-01
      • 2011-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多