搜索

首页  >  问答  >  正文

AWS Aurora MySQL数据库无法被Node Lambda函数查询

<p>我正在尝试使用Lambda函数向AWS Aurora MySQL数据库写入数据。</p> <h3>代码</h3> <p>出于某种原因,它似乎无法正常工作。到目前为止,我的代码非常简单,但无法正确执行。这是一个简单的Lambda函数,当用户注册到Cognito时调用,应该在SQL数据库中创建一个新条目,包含用户凭据。</p> <pre class="brush:php;toolbar:false;">const mysql = require('mysql') const db = mysql.createConnection({ host: "*****", port: *****, user: "*****", password: "*****", database: "*****", }) export const lambdaHandler = async (event: any, context: any,) => { const user = { uid: event.request.userAttributes.sub, username: event.request.userAttributes.nickname, email: event.request.userAttributes.email, } console.log("before query") const query = `INSERT INTO users (Uid, Username, Email) VALUES (${user.uid}, ${user.username}, ${user.email})` await db.query(query, (err: any, result: any) => { if (err) console.error(err) console.log("query response: " + result) }) console.log("after query") return event; };</pre> <p>函数的输出如下:</p> <pre class="brush:php;toolbar:false;">START RequestId: bb1d2143-97e4-4761-a48a-f482cf94f73b Version: $LATEST 2022-03-17T14:02:35.956Z bb1d2143-97e4-4761-a48a-f482cf94f73b INFO before query 2022-03-17T14:02:35.961Z bb1d2143-97e4-4761-a48a-f482cf94f73b INFO after query END RequestId: bb1d2143-97e4-4761-a48a-f482cf94f73b REPORT RequestId: bb1d2143-97e4-4761-a48a-f482cf94f73b Init Duration: 0.14 ms Duration: 138.07 ms Billed Duration: 139 ms Memory Size: 128 MB Max Memory Used: 128 MB</pre> <p>注意:查询函数没有找到日志记录(应该抛出错误或记录响应)</p> <h3>策略</h3> <p>Lambda函数的执行角色中包含以下策略:<code>AWSLambdaVPCAccessExecutionRole</code>和<code>AWSLambda_FullAccess</code></p> <h3>其他</h3> <p>Lambda函数和Aurora位于同一VPC的不同子网中。我不确定这是否会导致问题。但这不会导致函数抛出错误吗?类似于<code>missing authorization</code>的错误?</p> <p>我不明白我在这一点上还缺少什么</p>
P粉184747536P粉184747536486 天前703

全部回复(1)我来回复

  • P粉960525583

    P粉9605255832023-08-26 13:59:33

    问题在于db.query使用回调样式而不是promise样式。你需要将其转换为使用promises。

    一种方法是使用Util.promisify...

    const util = require('util');
    const mysql = require('mysql');
    
    const db = mysql.createConnection({
        host: "*****",
        port: *****,
        user: "*****",
        password: "*****",
        database: "*****",
    });
    
    // 将db.query转换为返回promise的函数
    const promisifiedQuery = util.promisify(db.query);
    
    export const lambdaHandler = async (event: any, context: any,) => {
        const user = {
            uid: event.request.userAttributes.sub,
            username: event.request.userAttributes.nickname,
            email: event.request.userAttributes.email,
        };
    
        console.log("before query");
    
        // 顺便说一下,这样做是不好的。请阅读有关如何避免SQL注入的内容。
        const query = `INSERT INTO users (Uid, Username, Email) VALUES (${user.uid}, ${user.username}, ${user.email})`;
    
        await promisifiedQuery(query).then(result => {
            console.log("query response: " + result)
            console.log("after query")
        }).catch(console.error)
    
        return event;
    };

    回复
    0
  • 取消回复