我正在尝试使用node(express,https modules)在高级别上执行以下操作:
问题是,如何从callbackExternalApi内发送响应?请参阅下面的代码和评论中的问题。
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)
谢谢,
Jatin
答案 0 :(得分:0)
我刚刚为response_R1定义了全局变量,并在requestHandlerExample回调中设置了这些变量。不确定这是否是最佳方法,但它确实有效。
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)