3

我的“handler.js”函数连接到 Postgres 数据库并使用 node.js 执行一些查询。我的函数在本地成功运行,但是当作为 AWS lambda 访问时,查询不起作用。

我还在“serverless.yml”中添加了相应的 vpc 安全组和子网 ID。

'Cloudwatch' 中的错误日志仅显示查询前后的 console.log 语句,并且函数因超时错误而终止。我无法弄清楚这个问题。

我在下面附上了示例“handler.js”代码:

var { Pool, Client } = require('pg');

export function apiTest(event, context, callback) {
  var connectionString = 'postgresql://username:password@database.server.com:xxxx/dbname';
  var client = new Client({
    connectionString: connectionString,
  })
  client.connect();
  console.log('Connected to PostgreSQL database');

  client.query('SELECT * from table', (err, res) => {
    console.log("inside query");
    var jsonString = JSON.stringify(res.rows);
    var jsonObj = JSON.parse(jsonString);

    const headers = {
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Credentials": true
    };

    // Return status code 500 on error
    if (err) {
      const response = {
        statusCode: 500,
        headers: headers,
        body: JSON.stringify({
          status: false
        })
      };
      callback(null, response);
      client.end();
      return;
    }

    const response = {
      statusCode: 200,
      headers: headers,
      body: JSON.stringify(jsonObj)
    };

    callback(null, response);
    console.log("query success")
    client.end()
    context.succeed(context);
  })
}
4

0 回答 0