开发者问题收集

尝试连接到 MySQL 数据库时出现“db 未定义”错误[关闭]

2021-07-20
1580

我正在尝试使用 Node.JS 构建 AWS Lambda 函数。这是我的代码。我对 Node.JS 非常陌生。

var response;

var mysql = require('mysql');
var con = mysql.createConnection({
    host: "*****.rds.amazonaws.com",
    user: "****",
    password: "***",
    database: "***",
    port: 3306
}); 
    

exports.lambdaHandler = async (event, context) => {

    con.connect();

    try{
        db.query( 'SELECT * from accounting_type' ).then( rows => {
            response = {
                'statusCode': 200,
                'body': JSON.stringify({
                    rows,
                })
            }
          } );
    }
    catch(err)
    {
        console.log(err);
        response = {
            'statusCode': 200,
            'body': JSON.stringify({
                err,
            })
        }
    }
    return response;

};

template.yaml

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  node2

  Sample SAM Template for node2
  
# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
  Function:
    Timeout: 3

Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
      CodeUri: hello-world/
      Handler: app.lambdaHandler
      Runtime: nodejs14.x
      Events:
        HelloWorld:
          Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
          Properties:
            Path: /hello
            Method: get
      Role: !GetAtt LambdaRole.Arn
      VpcConfig:
        SecurityGroupIds:
          - sg-041f2459dcd921e8e
        SubnetIds:
          - subnet-0456db2d
          - subnet-c6414cb
 
  LambdaRole:
    Type: 'AWS::IAM::Role'
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - lambda.amazonaws.com
            Action:
              - 'sts:AssumeRole'
      Path: /
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
      Policies:
        - PolicyName: root
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Action:
                  - ec2:DescribeNetworkInterfaces
                  - ec2:CreateNetworkInterface
                  - ec2:DeleteNetworkInterface
                  - ec2:DescribeInstances
                  - ec2:AttachNetworkInterface
                Resource: '*'

执行时,代码返回以下错误

START RequestId: 026dc152-40d0-49d3-b764-ded5f0cbc2b7 Version: $LATEST
2021-07-20T08:01:48.401Z    026dc152-40d0-49d3-b764-ded5f0cbc2b7    INFO    ReferenceError: db is not defined
    at Runtime.exports.lambdaHandler [as handler] (/var/task/app.js:20:9)
    at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)
END RequestId: 026dc152-40d0-49d3-b764-ded5f0cbc2b7
REPORT RequestId: 026dc152-40d0-49d3-b764-ded5f0cbc2b7  Duration: 1609.64 ms    Billed Duration: 1610 ms    Memory Size: 128 MB Max Memory Used: 80 MB  Init Duration: 152.15 ms    
XRAY TraceId: 1-60f682ea-66ea5e370df8860b12cf43fd   SegmentId: 5d2fad42374469c0 Sampled: true
2个回答

您正在将 mysql 连接游标分配给 con 变量,并在查询中使用 db ,因此 db 未定义。将 db 替换为 con ,如下所示:

con.query( 'SELECT * from accounting_type' , (err,rows) => {
            if(err){
               console.error(err)
               return
            }
            response = {
                'statusCode': 200,
                'body': JSON.stringify({
                    rows,
                })
            }
          });

已更新 答案以使用 (err,rows) 回调而不是 .then ,因为根据文档, .then 不可用。

Ankit Gupta
2021-07-20

这是因为您将引用的 db 定义为 con ,如下所示:

var con = mysql.createConnection({
    host: "*****.rds.amazonaws.com",
    user: "****",
    password: "***",
    database: "***",
    port: 3306
});

请通过将 con 替换为 db 或将 db 替换为 con 来更新您的代码>

Hycord
2021-07-20