Node.JS Lambda函数不返回JSON

时间:2016-08-17 13:00:23

标签: node.js aws-lambda

我是NodeJS和JS的新手(一般是PHP和C#家伙),所以我可以在下面的这个功能中使用一些帮助。

目标是接收JSON有效负载,连接到MySQL,然后在JSON响应中返回查询结果。我已经将它连接到数据库,我可以读取它收到的JSON数据(event.fieldname),但由于某种原因,它没有发回申请者_data变量的JSON。

我是否只是将变量放在错误的位置?当我运行下面的代码时,我会回来" {}"作为返回的数据。

提前感谢您的帮助!

NodeJS代码:

exports.handler = function(event, context, callback) {
console.log('Starting:');
console.log("Request received:\n", JSON.stringify(event));

var mysql = require('mysql');



var jsonconnection = mysql.createConnection({
    host: 'servername',
    user: 'username',
    password: 'password',
    database: 'database'
 });

jsonconnection.connect();
console.log('Connected to MySQL:');

jsonconnection.query('SELECT applicant_id FROM customers WHERE applicant_id = \'' + event.applicant_id + '\'',
    function(err,res){
    if(err) throw err;

    console.log('Row Details:', JSON.stringify(res));
        var applicant_data = {
            applicant_id : res.applicant_id
        };

    jsonconnection.end();

    context.succeed(applicant_data);
 })
};

2 个答案:

答案 0 :(得分:2)

我不熟悉AWS,但基于http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html,以下代码可能有用。

exports.handler = function (event, context, callback) {
    console.log('Starting:');
    console.log("Request received:\n", JSON.stringify(event));

    var mysql = require('mysql');

    var jsonconnection = mysql.createConnection({
        host: 'servername',
        user: 'username',
        password: 'password',
        database: 'database'
    });

    // Move applicant_data outside of query as it will be needed at the end in callback
    var applicant_data = {};

    jsonconnection.connect();
    console.log('Connected to MySQL:');

    jsonconnection.query('SELECT applicant_id FROM customers WHERE applicant_id = \'' + event.applicant_id + '\'',
        function (err, res) {
            if (err) throw err;

            console.log('Row Details:', JSON.stringify(res));
            applicant_data = {
                // Only use first row of data
                applicant_id: res[0].applicant_id;
            };

        });

    // Move connection end out side of query
    jsonconnection.end();

    // This should return your data, in JSON form
    callback(null, JSON.stringify(applicant_data));

    // I assume this is the correct use for succeed
    context.succeed();
};

答案 1 :(得分:0)

exports.handler = async (event) => {
    let jsonResponse = {"hello":"world"}
    const response = {
        statusCode: 200,
        body: JSON.stringify(jsonResponse),
    };
    return response;
};