urlopen module

The urlopen module provides APIs to establish a non-streaming connection with target servers by HTTP, HTTPS, Kafka, or IBM® MQ protocol and open files in the DataPower® file system. The APIs can also send and receive IBM MQ messages within a GatewayScript action.

To access the APIs in the urlopen module, use the require('urlopen') statement, such as var urlopen = require('urlopen');.

The urlopen module provides the urlopen.open() API to conduct the following behaviors.
  • When you want to use a user agent to initiate a request for a local service to establish a connection to the target server dynamically, create a user agent object and use it in the urlopen.open() API.
    UserAgent object
    The user agent object is used when the urlopen.open() API establishes a connection with the target server by HTTP, HTTPS, or IBM MQ protocol. The UserAgent object is assumed to represent the user agent object.
    HttpUserAgent object
    The HTTP-specific user agent object is used when the urlopen.open() API establishes a connection with the target server by HTTP or HTTPS protocol. The HttpUserAgent object is assumed to represent the HTTP-specific user agent object.
  • Establish a connection with the target server by HTTP, HTTPS, or IBM MQ protocol.
  • After connections are established, the response from the target server is handled by the callback parameter of the urlopen.open() API.
    urlopen.open() error responses
    When errors occurs, the urlopen.open() API can receives error codes that provide information to help you recover from errors.
    response object
    You can obtain the data by using a read API that is supported by the response object. The response object is assumed to be initialized by the urlopen.open() API. The read APIs include response.readAsBuffer(), response.readAsBuffers(), response.readAsXML(), and response.readAsJSON().
  • urlopen.open() to open files on the DataPower Gateway

UserAgent object

When you want to use a user agent to initiate a request for a local service to establish a connection to the target server dynamically, create the UserAgent object and call it in the urlopen.open() API.

When the GatewayScript file that includes the urlopen.open() API is called by the GatewayScript action, the GatewayScript user agent property overrides the specific property that is configured in the user agent for the XML manager or by variables. The specific property has the same functionality as the property of the UserAgent object.

Class constructor for creating the UserAgent object: urlopen.UserAgent class constructor

APIs for managing the UserAgent object: UserAgent APIs


urlopen.UserAgent class constructor

Use the urlopen.UserAgent() class constructor to create a UserAgent object.

new urlopen.UserAgent()

Creates and initializes a UserAgent object. The UserAgent object is used when the urlopen.open() API establishes a connection with the target server by HTTP, HTTPS, or IBM MQ protocol.

Syntax

new urlopen.UserAgent([ua_options])
ua_optionsA JSON object.
Example
Create and initialize the UserAgent object.
var urlopen = require(’urlopen’);
var UserAgent = new urlopen.UserAgent({persistentConnection: false});

UserAgent APIs

The UserAgent object provides the following APIs to manage the user agent.

All API specifications use the UserAgent object that is assumed to be defined by the urlopen.UserAgent() class constructor.
APIs for managing the UserAgent object.

UserAgent.prototype.get()

Returns a specific property value of the UserAgent object or returns the UserAgent object.

Syntax

UserAgent.prototype.get([name])
nameThe property name in the UserAgent object. The valid property name is persistenConnection.
When you specify the property name, the property value is returned. Otherwise, the UserAgent object is returned. When you specify an invalid property name, undefined is returned.

UserAgent.prototype.set()

Configures a specific property of the UserAgent object.

Syntax

UserAgent.prototype.set(name, value)
UserAgent.prototype.set({name: value})
nameThe property name in the UserAgent object. The valid property is defined in the ua_options parameter of the urlopen.UserAgent() API.
valueThe value to assign to the property.

HttpUserAgent object

When you want to use an HTTP-specific HttpUserAgent user agent to initiate a request for a local service to establish a connection to the target server dynamically, create the HttpUserAgent object and call it in the urlopen.open() API.

When the GatewayScript file that includes the urlopen.open() API is called by the GatewayScript action, the GatewayScript user agent property overrides the specific property that is configured in the user agent for the XML manager or by variables. The specific property has the same functionality as the property of the HttpUserAgent object.

Class constructor for creating the HttpUserAgent object: urlopen.HttpUserAgent class constructor

APIs for managing the HttpUserAgent object: HttpUserAgent APIs


urlopen.HttpUserAgent class constructor

The urlopen.HttpUserAgent class is derived from the urlopen.UserAgent class. Use the urlopen.HttpUserAgent() class constructor to create and initialize an HttpUserAgent user agent object.

new urlopen.HttpUserAgent()

Creates and initializes an HttpUserAgent user agent object. The HttpUserAgent object is used when the urlopen.open() API establishes a connection with the target server by HTTP or HTTPS protocol.

Syntax

new urlopen.HttpUserAgent([ua_options])
ua_optionsA JSON object that consists of properties that are specific to HTTP or HTTPS protocol.
Example
Create and initialize the HttpUserAgent object.
var urlopen = require(’urlopen’);
// define the http-specific user agent properties
var ua_options = {    
    'persistentConnection': false,
    'allowCompression': true,
    'followRedirect': flase,
    'maxRedirects': 16,
    'httpVersion': 2,
    'http2Required' : true,
    'rewriteHost': false
};
var HttpUserAgent = new urlopen.HttpUserAgent(ua_options);

HttpUserAgent APIs

The HttpUserAgent object provides the following APIs manage the HTTP-specific user agent.

All API specifications use the HttpUserAgent object that is assumed to be defined by the urlopen.httpUserAgent() class constructor.

HttpUserAgent.prototype.get()

Returns a specific property value of the HttpUserAgent object or returns the HttpUserAgent object.

Syntax

HttpUserAgent.prototype.get([name])
nameThe property name in the HttpUserAgent object. The valid properties are defined in the ua_options parameter of the urlopen.HttpUserAgent() API.
When you specify the property name, the property value is returned. Otherwise, the HttpUserAgent object is returned. When you specify an invalid property name, undefined is returned.

HttpUserAgent.prototype.set()

Configures a specific property of the HttpUserAgent object.

Syntax

HttpUserAgent.prototype.set(name, value)
HttpUserAgent.prototype.set({name: value})
nameThe property name in the HttpUserAgent object. The valid properties are defined in the ua_options parameter of the urlopen.HttpUserAgent() API.
valueThe value to assign to the property.

urlopen.open() to connect with target servers

The urlopen.open() API can establish a non-streaming connection with target servers. The urlopen.open() API can configure a user agent to initiate a request for a local service to establish a connection to the target server.

Syntax

var urlopen = require('urlopen');
urlopen.open(options, callback);
optionsSeveral properties that are grouped as a JSON object or a single URL specification for a target server.
callbackSpecifies an asynchronous function to be called after the urlopen.open() connects to the target, sends the data to the target, and the response header is parsed. The callback is in the function (error, response) { } form.

The URL of the target server supports HTTP, HTTPS protocols. For HTTPS protocol, ensure that the validation credentials in the TLS profile contains the correct authority. The authority is either the server-side certificate or the intermediate certificate authority for the target server.

When connections are established, the response from the responding server is read to obtain the data. The data is obtained by using one of the following read APIs. It is assumed that the response object is initialized by the urlopen.open() API.
  • response.readAsBuffer()
  • response.readAsBuffers()
  • response.readAsJSON()
  • response.readAsXML()

When HTTP or HTTPS urlopen.open() call completes, the connection to the target is disconnected. When there is an error, the connection closes automatically. Extra action is not needed to close a connection. The response.discard() and response.disconnect() APIs can discard data and disconnect an open connection.

Examples

  • Open a connection and read the response as a buffer object.
    var urlopen = require('urlopen');
    
    var options = {
                target: 'http://example.com/mydoc.json',
                method: 'post',
               headers: { 'X-My-Header1' : 'value1' , 'X-My-Header2' : 'value2' },
           contentType: 'text/plain',
               timeout: 60,
      sslClientProfile: 'aliceProxyForwardTrusted',
                  data: "Hello DataPower GatewayScript"};
    
    urlopen.open(options, function(error, response) {
      if (error) {
        // an error occurred during the request sending or response header parsing
        session.output.write("urlopen error: "+JSON.stringify(error));
      } else {
        // get the response status code
        var responseStatusCode = response.statusCode;
        var responseReasonPhrase = response.reasonPhrase;
        console.log("Response status code: " + responseStatusCode);
        console.log("Response reason phrase: " + responseReasonPhrase);
        // reading response data
        response.readAsBuffer(function(error, responseData){
          if (error){
            throw error ;
          } else {
            session.output.write(responseData) ;
          }
        });
      }
    });
  • Use the HttpUserAgent object to establish a connection to the target server and read the response as a buffer object.
    var urlopen = require(’urlopen’);
    // define the http-specific user agent properties
    var ua_options = {    
        'persistentConnection': true,
        'allowCompression': false,
        'followRedirect': true,
        'maxRedirects': 8,
        'http10Only': false,
        'rewriteHost': false
    };
    var HttpUserAgent = new urlopen.HttpUserAgent(ua_options);
    // define the urlopen options
    var options = {
        target: 'http://127.0.0.1:42410/echo',
        //If the target is HTTPS like 'https://127.0.0.1:42409/echo', supply a TLS client profile
        //sslClientProfile: 'aliceClientProfile'
        method: 'post',    
        headers: { 'X-My-Header1' : 'value1', 'X-My-Header2': 'value2' },
        contentType: 'application/json',
        timeout: 60,    
        data: "Hello DataPower GatewayScript",
        agent: HttpUserAgent
    };
    urlopen.open(options, function(error, response) {
      if (error) {
        // an error occurred during the request sending or response header parsing
        session.output.write("urlopen error: "+JSON.stringify(error));
      } else {
        // get the response status code
        var responseStatusCode = response.statusCode;
        var responseReasonPhrase = response.reasonPhrase;
        console.log("Response status code: " + responseStatusCode);
        console.log("Response reason phrase: " + responseReasonPhrase);
        // reading response data
        response.readAsBuffer(function(error, responseData){
          if (error){
            throw error ;
          } else {
            session.output.write(responseData) ;
          }
        });
      }
    });

urlopen.open() to open files on the DataPower Gateway

The urlopen.open() API to open files in the DataPower file system.

Syntax

var urlopen = require('urlopen');
urlopen.open(options, callback);
optionsA set of properties that are grouped as a JSON object or a single URL specification for a target file.
callbackSpecifies an asynchronous function to be called after the urlopen.open() connects to the target, sends the data to the target, and the response header is parsed. The callback is in the function (error, response) { } form.
The urlopen.open() API opens files that are specified with the target property. Local file access is distinguished by the protocol scheme.
  • You can access files with only the local:, store:, and temporary: protocol schemes.
  • File references are case-sensitive. For example, local:///myArea/myFile.XML is different from local:///myArea/myFile.xml.

Examples

  • Access mylocal_file.xml in local:///mylocal_directory, read the response as a Buffer object, and write the data to the output context.
    var urlopen = require('urlopen');
    urlopen.open("local:///mylocal_directory/mylocal_file.xml", function (error, response) {
      if (error) {
        session.output.write("openCallback error: " + error.errorMessage+"\n");
      }
      else {
        if (response.statusCode == 200) {
          // You have a 200, so you can read the file
          response.readAsBuffer (function (error, data) {
            session.output.write(data);
          });
        }
      }
    });
  • Attempt to access a nonexistent file returns a 404 File not found status code.
    var urlopen = require('urlopen');
    urlopen.open("local:///nonexisting.txt", function (error, response) {
      if (error) {
        session.output.write("openCallback error: " + error.errorMessage+"\n");
      }
      else {
        if (response.statusCode != 200) {
          // in this case, a non-200 statusCode indicates a problem reading the file
          session.output.write("Unable to open the file, statusCode: " +
                                response.statusCode + ", reasonPhrase: " +
                                response.reasonPhrase);
          response.disconnect();   // Optional: You can call response.disconnect()
                                   // to do an explicit disconnection. Without this
                                   // call, urlopen does an implicit disconnection
        }
        else {
          response.readAsBuffer(function(readError, data) {
            if (readError) {
              session.output.write("read file error: " + readError.toString());
            }
            else {
              session.output.write(data);
            }
          });
        }
      }
    });
  • Use a JSON object to specify the options parameter of the urlopen.open() API.
    var urlopen = require('urlopen');
    var open_options = {
      // the target URL
      target: 'local:///mylocal_directory/mylocal_file.xml',
      // method is optional, default is GET
      method: 'GET'
    };
    
    urlopen.open(open_options, function (error, response) {
      if (error) {
        session.output.write("openCallback error: " + error.errorMessage+"\n");
      }
      else {
        if (response.statusCode != 200) {
          // in this case, a non-200 statusCode indicates a problem reading the file
          session.output.write("Unable to open the file, statusCode: " +
                                response.statusCode + ", reasonPhrase: " +
                                response.reasonPhrase);
          response.disconnect(); // optional, urlopen will do an implicit disconnect()
        }
        else {
          response.readAsBuffer(function(readError, data) {
            if (readError) {
              session.output.write("read file error: " + readError.toString());
            }
            else {
              session.output.write(data);
            }
          });
        }
      }
    });

urlopen.open() formats for IBM MQ messages

The urlopen.open() API can send and receive IBM MQ messages within a GatewayScript action either dynamically or statically. You can use a URL dynamically created by various properties that are defined in the options parameter of the urlopen.open() API specific to IBM MQ protocols. You can also use a fully specified URL that can be defined in the options parameter of the urlopen.open() API or the non-options specification.

Syntax

var urlopen = require('urlopen');

var options =
{
  target: targetURL,
  data: message,
  headers: mqHeaders, 
  agent: UserAgent,
  parameter1: parameter_value1,
  parameter2: parameter_value2
  :
  parametern: parameter_valuen} ;

var mqHeader = { "MQMD" : {
                    "Version" : { $ , "1" },
                    "Format" : { $ , "MQSTR" }
               } };
urlopen.open(options, callback) ;
var urlopen = require('urlopen');
urlopen.open(targetURL, callback) ;
mqHeadersThe mqHeader identifies one or more header_name properties (such as, MQMD) and an associated header value containing a set of header_fields related to the specified header. The header may be specified as a JSON object or as an XML string.
targetURLThe name of the IBM MQ URL for this urlopen call. The protocol can be dpmq, idgmq, or mq. If targetURL is specified as a JSON property, the URL can be complete or partial. Parameter properties in the JSON object provide more specifications.
UAA UserAgent object that can initiate a request for a local service to establish a connection to the specified target server.
optionsConsists of properties that are used to specify IBM MQ behavior. The properties for GatewayScript are the same as correspondent attributes of the dp:url-open extension element. This includes the static and dynamic attributes for an IBM MQ queue manager. The list of properties available are those from the query parameters and dynamic mq:/// queue manager attributes of the dp:url-open IBM MQ extension element.
callbackSpecifies an asynchronous function to be called after the urlopen.open() connects to the target, sends the data to the target, and the response header is parsed. The callback is in the function (error, response) { } form.
  • For more information about options, refer to urlopen.open() API, and dp:url-open() generic and IBM MQ specific extension elements.
  • The IBM MQ disconnection is based on the cache timeout property of the queue manager.
  • In GatewayScript, the options parameter takes the form of a JSON object that specifies a keyword and a value (parameter: value). The properties contained in options are not case-sensitive. In XSLT, the properties contained in options take the form of parameters assigned values (parameter=value). For some properties contained in options, any value for the property defines its behavior. To not use this behavior, do not include this property. For more information, see the dp:url-open() IBM MQ extension element topic.
  • The non-options form is provided for consistency with other urlopen.open protocols. However, it has limited usefulness because of the default MQMD header and an inability to specify message content.
  • GatewayScript uses the camel case naming format for attributes and parameters. The parameters are for static and dynamic IBM MQ URLs. The attributes specify queue manager connection properties for dynamic IBM MQ URLs. For a list and description of these parameters, see url-open in the IBM MQ documentation.
    Attributes
    userName, channelName, channelTimeout, channelLimit, size, mqcspUserId, mqcspPassword
    Parameters
    requestQueue, replyQueue, timeOut, transactional, sync, gmo, pmo, parseHeaders, setReplyTo, asyncPut, browse, contentTypeHeader, contentTypeXPath, parseProperties, publishTopicString, selector, subscribeTopicString, subscriptionName
  • If the MQMD header is not defined in the options.headers, then a default MQMD header is used. The MQMD default has a MsgType field of 8. This usage implies that a datagram is used and no reply is expected. For more information about MQMD defaults and other parameter descriptions, refer to the IBM MQ documentation and search for MQMD.
  • The options parameter can be specified either individually or on the target URL. For example, the following options definitions are equivalent
      options = { target: 'idgmq://' + session.parameters.qm + '/?',
         requestQueue: session.parameters.requestQAlwaysReply,
           replyQueue: session.parameters.replyQ,
        transactional: true,
                 sync: true,
              timeOut: 10000,
              headers: { ... },
                 data: putData };

    and

    options = { target: 'idgmq://' + session.parameters.qm + '/?RequestQueue=' 
                 + session.parameters.requestQAlwaysReply + ';ReplyQueue=' + session.parameters.replyQ 
                 + ';Transactional=true;Sync=true;TimeOut=10000',
               headers: { ... },
                  data: putData };

    Specifying a property both individually and on the target URL results in an exception.

  • Status codes that are returned by IBM MQ.
    0
    Successful return.
    2xxx
    Error return.
  • For more information about IBM MQ headers, refer to the IBM MQ documentation and search for MQMD or search for data types that are used in the MQI.

Examples

  • Sample call to MQ in the options JSON object format. The headers label information in the options object is in a different format from the information for the other labels.
    var urlopen = require ('urlopen');
    var putData = '<MQRequest>Hello World</MQRequest>'; 
    
    var options =
    {
        target: 'mq://192.0.2.0:1414?QueueManager=QM1;UserName=mqm;Channel=QM1.SVRCONN;ChannelTimeout=10;'
                  + 'channelLimit=100;Size=1024000;RequestQueue=queue1;ReplyQueue=queue2',
      
         data : putData,
      headers : { MQMD   : { // JSON object for specified header_name
                                MQMD: { // JSON object for the MQMD header
                                       StructId : { $ : 'MD' } ,
                                        Version : { $ : '1'} ,
                                      }
                            } 
                  }
    };
    
    urlopen.open (options, function (error, response) {} );
  • An example shows how more complicated IBM MQ headers are set and used.
    var urlopen = require('urlopen');
    var putData = '<MQRequest>Hello World</MQRequest>'; 
    
    var urlopenHeaders = {
            // supply an MQMD header
            MQMD : {     // This MQMD is the header name.
                    MQMD: {  // JSON object for the MQMD header
                  StructId : { $ : 'MD' },
                   Version : { $ : '1' },
                    Format : { $ : 'MQHRF2' },
                    MsgType : { $ : '1' },
               ReplyToQMgr : { $ : session.parameters.qm },
                  ReplyToQ : { $ : session.parameters.replyQ },
                    Expiry : { $ : '10000' },
               Persistence : { $ : '1' },
                  Priority : { $ : '10' },
               PutApplType : { $ : '6' },
               PutApplName : { $ : 'My Datapower IBM MQClient' }, 
            ApplOriginData : { $ : 'testUrlOpenMPGW' },
          ApplIdentityData : { $ : 'mqUrlOpenDemo.js' } }
                   },
             // supply an MQRFH2 header
             MQRFH2 : { 
               MQRFH2: {
                     Format: { $ : 'MQSTR' },
              NameValueData: {
                       NameValue: [
                                    { mcd : { property1 : { $ : '1111' } } },
                                    { jms : { property2 : { '@dt': 'string', $ : 'value2'} } },
                                    { usr : { group : {
                                                 property3 : { $ : 'value3' },
                                                 property4 : { $ : 'value4'} } } }
                                  ] }
                   }
             }
     };
    
      var options = {
                         target : 'idgmq://' + session.parameters.qm + '/?RequestQueue='
                             + session.parameters.requestQ,
                       headers : urlopenHeaders,
                        data : putData,
               replyQueue : session.parameters.replyQ,
                      pmo : 2052  // MQPMO_NO_SYNCPOINT (4) + MQPMO_SET_ALL_CONTEXT (2048) };
    
     try {
           urlopen.open(options, function(connectError, response) {
                 if (connectError) {    
                       var errorMessage = connectError + 'errorCode='
                                            + connectError.errorCode.toString(16);
                       console.error(errorMessage);
                       session.output.write(errorMessage);
    
                  } else {
                       var responseCode = response.statusCode; 
                       if (responseCode == 0) {
                             console.info('Received MQ ' + response.statusCode
                                           + ' for target ' + options.target); 
                             response.readAsXML(function(readAsXMLError, xmlDom) {
                                  if (readAsXMLError) {
                                      var errorMessage = 'Error on readAsXML: ' + readAsXMLError;
                                      console.error(errorMessage);
                                      response.readAsBuffer(function(readAsBufferError, buffer) {
                                           if (readAsBufferError) { 
                                                 var errorMessage = 'Error on readAsBuffer: '
                                                                     + readAsBufferError;
                                                 console.error(errorMessage);
                                                 session.output.write(errorMessage);
                                           } else {
                                                 console.info('MQ Response headers: ' + response.headers);
                                                 session.output.write(buffer);
                                           }
                                });
                        } else { 
                            console.info('MQ Response headers: ' + response.headers);
                            session.output.write(xmlDom);
                        }
                   });
               } else {
                  var errorMessage = 'Received MQ ' + response.statusCode
                                    + ' for target ' + options.target;
                  session.reject(errorMessage);
               }
            }
        }); 
    } catch (err) {
         var errorMessage = 'Thrown error on urlopen.open for target ' + options.target + ': '
                             + err.message + ', error object errorCode=' + err.errorCode.toString(16);
         session.reject(errorMessage);}
  • An example of how options JSON object can be declared for an MQMP header.
    var urlopenMQMPHeaders = {
            // supply an MQMD header
            MQMD : {    // The property name 'MQMD' is the header name.
                    MQMD: {   // This 'MQMD' represents the root property.
                              StructId : { $ : 'MD' },
                               Version : { $ : '2' },
                                Format : { $ : 'MQSTR' },
                               MsgType : { $ : '1' },
                           ReplyToQMgr : { $ : session.parameters.qm },
                              ReplyToQ : { $ : session.parameters.replyQ },
                                Expiry : { $ : '10000' },
                           Persistence : { $ : '1' },
                              Priority : { $ : '10' },
                           PutApplType : { $ : '6' },
                           PutApplName : { $ : 'My Datapower IBM MQClient' },
                        ApplOriginData : { $ : 'testUrlOpenMPGW' },
                      ApplIdentityData : { $ : 'testUrlOpen.js' }
                          }
                   },
            // supply an MQMP header
            MQMP : {   // The property name 'MQMP' is the header name.
                       MQMP: { // This 'MQMP' represents the root property.
                                     Property : [ // an array of property
                                             { '@name' : 'car.brand', '@type':'string', $ : 'DataPower'},
                                             { '@name' : 'car.color', '@type':'string', $ : 'GREEN'},
                                             { '@name' : 'car.year', '@type':'int32', $ : '2005' }
                                                ]
                             }
                   }
    };
    options = {
        target: 'idgmq://' + session.parameters.qm + '/?RequestQueue=GATEWAYSCRIPT.PROPERTIES.REQUEST' 
                          + ';ReplyQueue=' + session.parameters.replyQ,
       headers: urlopenMQMPHeaders,
          data: putData,
           pmo: 2052  // MQPMO_NO_SYNCPOINT (4) + MQPMO_SET_ALL_CONTEXT (2048)};
    };

response object

The response object represents the response of a network connection in the callback function. In all APIs specifications that use the response object, where not specified, the response object is assumed to be initialized by urlopen.open() API. The response object is the second parameter of the callback function that is a parameter of the urlopen.open() API.


response.discard()

Discard the response. This API instructs the urlopen.open() API to receive but discard the bytes of the response message efficiently. You can access the header metadata from the response object. Depending upon the error there might be no error to discard or disconnect. An important use of response.discard() is to obtain the status code of the failing response.

Syntax

response.discard(function(error) { })
errorThe error object in case an error occurs during the response.discard() API.

response.disconnect()

No response content is returned. This API instructs the urlopen.open() API to stop immediately the back-end connection. For responses besides IBM MQ responses, this action eliminates the latency of reading a large payload but it can have adverse affects if persistent connections are used.

Syntax

response.disconnect()

response.get()

Read the response header.

Syntax

response.get([headername])
response.get(options, headername)
headernameSpecify the optional header name to retrieve a specific response header.
optionsA set of properties that are grouped as a JSON object.

The response.get() API returns the specific response header when the headername parameter is specified. For example, response.get('h1') retrieves the h1 header, which is equivalent to response.headers.h1 and response.headers['h1'].

  • If the header name is not provided, response.get() is equivalent to response.headers that contains the entire collection of response headers.
  • The response.get(headername) form reads the unstructured (raw) header. The response.get(options, headername) form reads the structured header as specified by the type in the options. For more information about structured and unstructured headers, see the header module.
Get an IBM MQ response header.
var urlopen = require('urlopen');  // access the module
urlopen.open (options, function (error, response) {

//  get the response as a JSON object representing an MQ header structure
var structured = response.get({type: 'mq'}, 'MQMD');  

response.headers

Read the entire collection of response headers into a JSON object.

Syntax

response.headers

response.readAsBuffer()

Read the response into a Buffer object.

Syntax

response.readAsBuffer(function(error, buffer) { })
errorThe error object in case an error occurs during the response.readAsBuffer() API.
bufferThe buffer location that contains the data that is read by a successful response.readAsBuffer() API.
The response.readAsBuffer() API reads the data as a buffer object. If reading is successful, the data becomes the value of the buffer variable buffer. Otherwise, a GatewayScript error object error describes the error.

response.readAsBuffers()

Read the response into a Buffers object.

Syntax

response.readAsBuffers(function(error, buffers) { })
errorThe error object in case an error occurs during the response.readAsBuffers() API.
buffersThe Buffers object containing the data that is read by a successful response.readAsBuffers() API.
The response.readAsBuffers() API reads the data as a Buffers object. If reading is successful, the data becomes the value of the buffers variable. Otherwise, a GatewayScript error object error describes the error.

response.readAsJSON()

Read the response into a JSON object.

Syntax

response.readAsJSON(function(error, json) { })
errorThe error object in case an error occurs during the response.readAsJSON() API.
jsonThe JSON object that contains the data that is read by a successful response.readAsJSON() API.
The response.readAsJSON() API reads the data and parses it into a JSON object. If reading is successful, the data becomes the value of the json variable. Otherwise, a GatewayScript error object error describes the error.

response.readAsXML()

Read the response into an XML object.

Syntax

response.readAsXML function(error, xml) { })
errorThe error object in case an error occurs during the response.readAsXML() API.
xmlThe XML object that contains the data that is read by a successful response.readAsXML() API.
The response.readAsXML() API reads the data as a NodeList. If reading is successful, the data becomes the value of the nodelist variable. Otherwise, a GatewayScript error object error describes the error.

response.reasonPhrase

Reads the reason phrase from the urlopen.open() response. Reason phrases are only available for HTTP targets.


response.statusCode

Reads the status code from the urlopen.open() response.


response.types

Returns an array of supported structure types of the urlopen.open() response headers.

Get the types of response headers.
var urlopen = require('urlopen');

var options = {
target: 'idgmq://qmgr/?RequestQueue=q1', 
// Note that inMQMD and inMQRFH2 headers are in the same format
// as shown in urlopenMQMPHeaders in a previous example.
headers: {
   'MQMD': inMQMD,
   'MQRFH2': inMQRFH2
  },
} ;
urlopen.open (options, function (error, response) {
// consume response MQMD header as JSON
var outMQMD = response.get({type: 'mq'}, 'MQMD');
// returns ['mq']
var types = response.types;
...
});