Node.JS Lambda 函数不返回 JSON

Jos*_*osh 7 node.js aws-lambda

我是 NodeJS 和 JS 的新手(主要是 PHP 和 C# 人),所以我真的可以在下面的这个函数中使用一些帮助。

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

我只是在错误的位置有变量吗?当我运行下面的代码时,我只是返回“{}”作为返回的数据。

在此先感谢您的帮助!

节点代码:

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);
 })
};
Run Code Online (Sandbox Code Playgroud)

Joh*_*Siu 4

我不熟悉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();
};
Run Code Online (Sandbox Code Playgroud)