Jatin Jatin - 3 years ago 105
Node.js Question

how to access node express response object in this case?

I am trying to do the following on a high level, using node (express, https modules):


  1. listen for POST requests (say R1) on /example endpoint (express app)

  2. read the post payload from the request, process it repackage it and make an https POST request (say R11) to an external REST API.

  3. read the post payload from the response to R11, process it repackage it and send as a response to R1.



Problem is, how to send response from within callbackExternalApi ? Please see code below and question in comments.

const callbackExternalApi =
function (response) {
response.on('data',
function(data) {
// do some processing on data
var processedData = ...
**// I want response_R1 over here
// so that I can do the following
response_R1.send(processedData)
// how do I get response_R1 over here??**
})
}

const requestHandlerExample =
function (request_R1, response_R1) {

// payload
var postBodyJson = '' // some payload here

// headers
var postHeaders = {
'content-type' : 'application/json',
'accept' : 'application/json'
}

// options
var postOptions = {
'host' : 'localhost',
'port' : '9000',
'path' : '/external/rest/api',
'method' : 'POST',
'headers' : postHeaders
}

// do the post call
var postRequest = _httpsModule.request(postOptions, callbackExternalApi)
postRequest.write(postBodyJson);
postRequest.end();
postRequest.on('error', function(error) {
console.error('an error occured'+error)
})
}

_app.post('/example', requestHandlerExample)


Thanks,

Jatin

Answer Source

I just defined global variables for response_R1 and set those in the requestHandlerExample callback. Not sure if that's the best approach, but it works.

var _response_R1

const callbackExternalApi = 
function (response) {
    response.on('data', 
        function(data) {
            // do some processing on data
            var processedData = ...
            _response_R1.send(processedData)
        })
}

const requestHandlerExample = 
function (request, response) {
    _response_R1 = response // set this for use in callbackExternalApi

    // payload
    var postBodyJson = '' // some payload here

    // headers
    var postHeaders = {
    'content-type'  : 'application/json',
    'accept'        : 'application/json'
    }

    // options
    var postOptions = {
        'host'      : 'localhost',
        'port'      : '9000',
        'path'      : '/external/rest/api',
        'method'    : 'POST', 
        'headers'   : postHeaders
    }

    // do the post call
    var postRequest = _httpsModule.request(postOptions, callbackExternalApi)
    postRequest.write(postBodyJson);
    postRequest.end();
    postRequest.on('error', function(error) {
        console.error('an error occured'+error)
    })
}

_app.post('/example', requestHandlerExample)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download