I have created an API Gateway which routes to AWS Lambda function (Node 8.10). The Lambda function makes POST request to a third party API and should return the response (status and message) back to API GATEWAY. What is happening is that I am able to successfully call third party API (its a post request so I can check that Lambda is doing its job) but when I send response back to API GATEWAY, it is not able to send the updated response.
The reason for this is that Lambda is calling callback(null, response) almost immediately , whereas response from third party API comes later and hence response object is updated later (I can confirm that through console logs). I have written one callback(null, response) inside the callback function as can be seen from attached code snippet but it seems API GATEWAY considers the earliest callback response. How can I make sure that LAMBDA function sends the updated response only. Following is the attached code:
const https = require('https');
exports.handler = async (event, context, callback) => {
var body = JSON.parse(event.body);
var postData = JSON.stringify(body);
const options = {
method: 'POST',
hostname: app_url
path: path_value
port: 443,
headers: {
'accept': 'application/json',
'Content-Type': 'application/json',
'Content-Length': postData.length,
'Authorization': auth_token_value
}
};
var response = {};
var dataStr = "";
const req = https.request(options, (res) => {
response.statusCode = res.statusCode;
response.headers = res.headers;
res.on('data', (d) => {
dataStr += d;
});
res.on('end', () => {
response.body = dataStr;
console.log(response);
callback(null, response);
});
});
req.write(postData);
req.end();
console.log(response);
callback(null, response);
}
req.write(postData)andreq.end(). I'm just guessing as, these are not required in lambda. This is not normal nodeJs server. This isserverless.req.end()can be removed though it does not solve the issue - it was a redundant line. I would needreq.write(postData)otherwise I would not be able to post the payload. @NAVIN