简体   繁体   中英

Pass variable value from JavaScript function to SQL query AWS Lambda

I am making a serverless phone directory search application. There are two files: index.html and lambda_function.py

The index.html has a JS function, a text field for entering a name, and a search button. Lambda_function.py contains code for handling CSV.

I am unable to pass values from the index.html textbox to the lambda_function.py SQL query. The browser debugger reports an error.

errorMessage: "name 'name_Person' is not defined"
​
errorType: "NameError"
​
stackTrace: Array [ "  File \"/var/task/lambda_function.py\", line 12, in lambda_handler\n    sql_q = \"SELECT * FROM s3object s where s.\\\"Name\\\" = ('%s')\" %name_Person\n" ]

What is the correct way to pass the name entered by the user into the SQL query in this case?

Index.html content

<script>

    function FindInPhoneBook() {
        var name_person = $('#name').val();
        if (name_person == "")
            return;
        fetch('https://xxx.eu-west-3.amazonaws.com/SecondStage', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: '{ "command": "find", "name_Person":"'+name_person+'" }'
        }).then(function(data) {
            $('#list_personal').val(data)
            find();
            data.json().then(function(bodyData) {
                console.log(bodyData);
                $('#list_personal').text(bodyData);
            })
        })
    }
        
</script>
<div class = "border">


<input id="name" type="text">
<button onclick="FindInPhoneBook()">
Find
</button>  
<br></br>
<div id='list_personal'></div>
</div>

lambda_function.py content
import json
import boto3
def lambda_handler(event, context):
    res = ''
    s3 = boto3.client('s3')

    if(len(event) == 0):
        with open('index.html','r') as file:
            return file.read()
    elif event['command'] == 'find':
        #name = 'Vinod'
        sql_q = "SELECT * FROM s3object s where s.\"Name\" = ('%s')" %name_Person
        resp = s3.select_object_content(
            Bucket='chumbacket',
            Key='sample_data.csv',
            ExpressionType='SQL',
            Expression=sql_q,
            InputSerialization = {'CSV': {"FileHeaderInfo": "Use"}, 'CompressionType': 'NONE'},
            OutputSerialization = {'CSV': {}},
        )
        
        for event in resp['Payload']:
            if 'Records' in event:
                records = event['Records']['Payload'].decode('utf-8')
            
        return records
    elif 1==1:
        pass
        
    return res

You can pass data to a Lambda function by invoking the Lambda function using the Lambda API and calling the invoke method. You can pass data to it as JSON data. Here is an example implemented in Java (but will show you how to use the Lambda API to invoke a Lambda operation and pass data)

https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javav2/example_code/lambda/src/main/java/com/example/lambda/LambdaInvoke.java

You can see AWS SDK for JavaScript v3 AWS Lambda examples here. This is the API to use from within a script tag in your HTML.

https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascriptv3/example_code/lambda

It looks like you forgot to define your name_Person variable. Try adding this before the SQL query:

name_Person = event['name_Person']

Since it seems like you elif event['command'] == 'find': conditional is triggering fine, the event should have name_Person in there too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM