I've run into some trouble with a site I am building. It used AWS lambda functions. I am building and deploying on AWS CodeStar.
The site strips the URL parameter (e.g. /BTC), sends that to external API endpoint, which returns some JSON data. I can display the entire JSON response using body: JSON.stringify(response)
, so it is definitely coming through from the API. However, I would like to the JSON values to HTML markup before sending back to the client. Yet, when I do something like var html = '<h1>JSON.stringify(response['DISPLAY']['BTC']['USD']['MARKET'])</h1>';
. I receive an Internal Server Error - Malformed Request.
I can't figure this out. I'm fairly new to the world of AWS, so may be overlooking something, I've looked around in the docs and can't seem to find anything related to this.
Also, when I had the JSON.stringify
output displaying on the webpage. If I re-parsed this in the browser console, response['DISPLAY']['BTC']['USD']['MARKET']
returned a value - so I am fairly sure the syntax for the payload data is correct.
exports.get = function(event, context) {
var ticker = event.pathParameters.currency;
rp(`https://min-api.cryptocompare.com/data/pricemultifull?fsyms=${ticker}&tsyms=USD`)
.then(function (response) {
var html = `<h1>${JSON.stringify(response['DISPLAY']['BTC']['USD']['MARKET'])}</h1>`;
context.succeed({
statusCode: 200,
body: html,
headers: {'Content-Type': 'text/html'}
});
})
.catch(function (err) {
console.log('error: ', err);
});
};
Any help would be appreciated! Happy to provide more info if required.
This is caused by a combination of a couple of things, as far as I can tell:
.catch
block you are not calling context.error
. In other words, if there's an error in your lambda function, the lambda function never signals that it's finished executing properly to the invoker. API gateway throws up its hands in despair and spits out a 502
error.response
is a string, so when you try to access its properties, you cause an exception and end up in your .catch
block. First you need to JSON.parse(response)
Here's a helpful note: whenever you call console.log
, the log output can be found in CloudWatch > Logs > /aws/lambda/<your-lambda-name>
. This can be useful for figuring out why/where things are breaking.