【问题标题】:How can i respond with JSON with a Lambda function如何使用 Lambda 函数响应 JSON
【发布时间】:2016-11-29 16:21:46
【问题描述】:

下面我尝试使用 JSON 格式的天气响应 GET。我正在尝试使用 const 来传递响应。这似乎不起作用。我在控制台中得到响应和天气,但没有向客户端返回任何内容。

'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);
        callback(response);
      });
    });
}

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)
        break;
    case 'GET':
       // dynamo.scan({ TableName: event.queryStringParameters.TableName }, done);
        done(get_json("http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=92f14e06a6652e81a5a58bd13d152f70", callback,  function (resp) {
        callback(resp);
         })); 
        break;
}

};

【问题讨论】:

    标签: javascript json node.js lambda


    【解决方案1】:

    get_json() 不返回任何内容,因此将其传递给done 绝对是错误的做法。

    看起来你需要这样做:

    get_json(
       "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=92f14e06a6652e81a5a58bd13d152f70", 
        resp => done(null, resp)
    ); 
    

    【讨论】:

    • 这太棒了。非常感谢
    猜你喜欢
    • 2021-10-23
    • 2016-02-07
    • 1970-01-01
    • 1970-01-01
    • 2021-11-05
    • 1970-01-01
    • 2016-08-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多