Context: I’m trying to make a POST request to a AWS lambda function written in python from JavaScript. I will then enter the information in the POST request into a Database.
Problem: I can’t seem to figure out how to get the information out of the POST request. and store it into variables.
I’ve tried to use the event[‘Username’] which in the testing simulation provided by AWS works although in practice doesn’t.
<form method="POST" action="https://fake.execute-api.us-east-1.amazonaws.com/Prod/RegisterUser"> <label for="Username">Username:</label><br> <input type="text" id="Username" name="Username" value=""><br> <label for="password">Password:</label><br> <input type="text" id="Password" name="Password" value=""><br><br> <input type="submit" id="submit" value="Submit" > </form>
POST /Prod/RegisterUser HTTP/1.1 Host: fake.execute-api.us-east-1.amazonaws.com User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate Content-Type: application/x-www-form-urlencoded Content-Length: 24 Connection: close Upgrade-Insecure-Requests: 1 Username=jat&Password=sa
import pymysql import json #endpoint = 'fake.us-east-1.rds.amazonaws.com' #username = 'admin' #password = 'admin' #database_name = 'fake' #connection #connection = pymysql.connect(endpoint, user=username, passwd=password, db=database_name) def lambda_handler(event, context): user = event['Username'] password = event['Password'] return { "Username": user, "Password":password }
Advertisement
Answer
SOLVED:
I found that posting directly to the AWS Lambda wasn’t working because of the string format. The AWS Lambda requires JSON format with use of JSON.stringify().
<form onsubmit="submitData();return false;"> <label for="Username">Username:</label><br> <input type="text" id="Username" name="Username" value=""><br> <label for="password">Password:</label><br> <input type="text" id="Password" name="Password" value=""><br><br> <input type="submit" id="submit" value="Submit" > </form>
function submitData() { var user = document.getElementById("Username").value var pass = document.getElementById("Password").value var json = { Username: user, Password: pass }; $.ajax({ type: "POST", url: "https://fake.execute-api.us-east-1.amazonaws.com/Prod/RegisterUser", data: JSON.stringify(json), beforeSend: function() { console.log("Before"); $("#submit").attr('disabled', true); }, success: function(response){ console.log(response); $("#submit").attr('disabled', false); } }); }
import pymysql import json def lambda_handler(event, context): resp = event return { "Username:": resp["Username"], "Password": resp["Password"] }