scottmont scottmont - 1 year ago 106
Javascript Question

How can i respond with JSON with a Lambda function

Below I am trying to repond to a GET with the weather in JSON format. I am attempting the use the const done in order to deliver the response. This does not seem to work. I get the response and weather in console but return nothing to the client.

'use strict';

console.log('Loading function');
const doc = require('dynamodb-doc');
const http = require('http');
const dynamo = new doc.DynamoDB();

function get_json(url, callback) {
http.get(url, function(res) {
var body = '';
res.on('data', function(chunk) {
body += chunk;

res.on('end', function() {
var response = JSON.parse(body);

exports.handler = (event, context, callback) => {

const done = (err, res) => callback(null, {
statusCode: err ? '400' : '200',
body: err ? err.message : JSON.stringify(res),
headers: {
'Content-Type': 'application/json',

switch (event.httpMethod) {
case 'DELETE':
dynamo.deleteItem(JSON.parse(event.body), done)
case 'GET':
// dynamo.scan({ TableName: event.queryStringParameters.TableName }, done);
done(get_json(",uk&appid=92f14e06a6652e81a5a58bd13d152f70", callback, function (resp) {


Answer Source

get_json() doesn't return anything, so passing it into done is definitely the wrong thing to do.

It looks like you need to do this:

    resp => done(null, resp)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download