AWS API gateway unreacheable from S3 webpage - javascript

I am trying to add a form contact to a AWS S3 static web page with API Gateway, Lambda and SES
I checked and followed many guides, so far the API gateway and Lambda together can send email properly. I even tested successfully with postman APP in my home computer.
I guess the form webpage script does not called or it is bad created, please help on check it. The form does not received fail response only reset itself.
This is AWS lambda function
var AWS = require('aws-sdk');
var ses = new AWS.SES();
var RECEIVER = 'xxxxx#gmail.com';
var SENDER = 'xxxxx#gmail.com';
var response = {
"isBase64Encoded": false,
"headers": { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*'},
"statusCode": 200,
"body": "{\"result\": \"Success.\"}"
};
exports.handler = function (event, context) {
console.log('Received event:', event);
sendEmail(event, function (err, data) {
context.done(err, null);
});
};
function sendEmail (event, done) {
var params = {
Destination: {
ToAddresses: [
RECEIVER
]
},
Message: {
Body: {
Text: {
Data: 'name: ' + event.name + '\nphone: ' + event.phone + '\nemail: ' + event.email + '\ndesc: ' + event.desc,
Charset: 'UTF-8'
}
},
Subject: {
Data: 'Website Referral Form: ' + event.name,
Charset: 'UTF-8'
}
},
Source: SENDER
};
ses.sendEmail(params, done);
}
the form webpage that it called AWS function is
<html>
<head>
</head>
<body>
<form id="contact-form" method="post">
<h4>Name:</h4>
<input type="text" style="height:35px;" id="name-input" placeholder="Enter name here" class="form-control" style="width:100%;" /><br/>
<h4>Phone:</h4>
<input type="phone" style="height:35px;" id="phone-input" placeholder="Enter phone number" class="form-control" style="width:100%;"/><br/>
<h4>Email:</h4>
<input type="email" style="height:35px;" id="email-input" placeholder="Enter email here..." class="form-control" style="width:100%;"/><br/>
<h4>How can we help you?</h4>
<textarea id="description-input" rows="3" placeholder="Enter your message..." class="form-control" style="width:100%;"></textarea><br/>
<div class="g-recaptcha" data-sitekey="6Lc7cVMUAAAAAM1yxf64wrmO8gvi8A1oQ_ead1ys" class="form-control" style="width:100%;"></div>
<button type="button" onClick="submitToAPI(event)" class="btn btn-lg" style="margin-top:20px;">Submit</button>
</form>
</body>
<script>
function submitToAPI(e) {
e.preventDefault();
var URL = "https://"awsdata".amazonaws.com/probado/sndemail";
var name = document.getElementById("name-input").value;
var phone = document.getElementById("phone-input").value;
var email = document.getElementById("email-input").value;
var desc = document.getElementById("description-input").value;
if (name=="" || phone=="" || email=="" || desc=="")
{
alert("Please Fill All Required Field");
return false;
}
nameRE = /^[A-Z]{1}[a-z]{2,20}[ ]{1}[A-Z]{1}[a-z]{2,20}/;
if(!nameRE.test(name)) {
alert("Name entered, is not valid");
return false;
}
phoneRE = /^([0|\+[0-9]{1,5})?([7-9][0-9]{9})$/;
if(!phoneRE.test(phone)) {
alert("Phone number entered, is not valid");
return false;
}
emailRE = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(!emailRE.test(email)) {
alert("Email Address entered, is not valid");
return false;
}
var data = {
name : name,
phone : phone,
email : email,
desc : desc
};
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "<URL for API gateway>");
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.send(JSON.stringify(data));
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4) {
var response = JSON.parse(xmlhttp.responseText);
if (xmlhttp.status === 200 ) {
console.log('successful');
document.getElementById("contact-form").innerHTML = "<h1>Thank you for your message/feedback<br>our team will get back to you soon!</h1>";
} else {
console.log('failed');
}
}
}
document.getElementById('contact-form').reset();
}
</script>
</html>
API Gateway CORS

The form has to be inside the body and put the script inside the head...
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<script> your own script like the one above... </script>
</head>
<body>
<form> user form... </form>
</html>

Related

POST https://example.com/api/payment/verify net::ERR_CONTENT_LENGTH_MISMATCH 200 (OK)

I am facing this error when I run this code on a Linux server, but the code seems to work fine in the local host.
the error points me to fetch inside the function laSt in the following code.
and then I also get a Uncaught (in promise) TypeError: Failed to fetch in this line return response.json(); inside that function only.
<p style="font-family: 'Manrope', sans-serif; padding-left: 10px;"> Please wait while we fetch you the payment snippet.</p>
<div class="">
<input style="visibility: hidden;" type="text" id="rzp-text">
<button class="buttonDes" id="order-button1">Click to proceed</button>
</div>
<div id="paymentDetails"></div>
<script src="https://checkout.razorpay.com/v1/checkout.js"></script>
<script>
document.getElementById("order-button1").addEventListener('click', laSt);
//document.getElementById("order-button1").onclick = laSt();
async function laSt(){
let url = '/api/payment/verify';
let params = {
razorpay_order_id: document.getElementById('order-id').value,
razorpay_payment_id: document.getElementById('order-pay-id').value,
razorpay_signature: document.getElementById('order-sig').value
};
await fetch(url, {
method: 'POST', // or 'PUT'
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(params); // body data type must match "Content-Type" header
}).then(function (response) {
return response.json();
}).then(function (muutuja) {
document.getElementById('success').value = muutuja.status;
console.log(muutuja.status);
});
return goToUrl();
}
function goToUrl(){
if(document.getElementById('success').value === 'success'){
window.location = "https://example.com/success" || "https://www.example.com/success" || process.env.port + '/success'
//redirect to orders
} else if (document.getElementById('success').value === 'failure') {
window.location = 'https://example.com/checkout' || "https://www.example.com/checkout" || process.env.port + '/checkout'
}
}
</script>
<div style="visibility: visible;">
<label for="">Order id :</label>
<input type="text" id="order-id">
<label for="">Payment id :</label>
<input type="text" id="order-pay-id">
<label for="">Order signature :</label>
<input type="text" id="order-sig">
<input type="text" id="success">
</div>
<%- include ('../partials/footer'); -%>
this is what the backend code looks like
router.post("/api/payment/verify", (req, res) => {
body = req.body.razorpay_order_id + "|" + req.body.razorpay_payment_id;
let expectedSignature = crypto
.createHmac("sha256", 'thisisanincorrectkey').update(body.toString())
.digest("hex");
let response = {status: "failure"};
console.log(expectedSignature + " " + req.body.razorpay_signature);
if(expectedSignature === req.body.razorpay_signature){
response = {status: "success"};
}
res.send(response);
});

Local storage is missing an ID Token, Please authenticate

Getting Local storage is missing an ID Token, Please authenticate. My end goal is to get the user signed up through AWS Cognito and then add a row in my DynamoDB table. I am able to get the user in the user pool but not able to add the details to DynamoDB. Unable to figure out the error any help will be appreciated.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<!-- Javascript SDK-->
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.410.0.min.js"></script>
<script src="https://rawgit.com/aws/amazon-cognito-identity-js/master/dist/aws-cognito-sdk.min.js"></script>
<script src="https://rawgit.com/aws/amazon-cognito-identity-js/master/dist/amazon-cognito-identity.min.js"></script>
</head>
<body>
<fieldset >
<h1 class="h3 mb-3 font-weight-normal" id="titleheader">Register an Account</h1>
<form>
<input type="email" class="form-control" id="emailInputRegister" placeholder="Email" pattern=".*" required><br><br>
<input type="password" class="form-control" id="passwordInputRegister" placeholder="Password" pattern=".*" required><br><br>
<input type="personalname" class="form-control" id="personalnameRegister" placeholder="First Name" pattern=".*" required><br><br>
<input type="personalname2" class="form-control" id="personalnameRegister2" placeholder="Last Name" pattern=".*" required><br><br>
<input type="text" class="form-control" id="organizationRegister" placeholder="Organization" pattern=".*" required><br><br>
<input type="text" class="form-control" id="jobTitleRegister" placeholder="JobTitle" pattern=".*" required><br><br>
<input type="tel" class="form-control" id="phone" placeholder="Cell Phone Number" pattern=".*" required><br><br>
<button id="mainbutton" class="btn btn-lg btn-primary btn-block" type="button" onclick="registerButton()" >Sign Up</button>
</form>
</fieldset >
<script>
var username;
var password;
var firstname;
var lastname;
var jobtitle;
var organization;
var phonenumber;
var poolData;
function registerButton() {
username = document.getElementById("emailInputRegister").value;
password = document.getElementById("passwordInputRegister").value;
firstname = document.getElementById("personalnameRegister").value;
lastname = document.getElementById("personalnameRegister2").value;
organization = document.getElementById("organizationRegister").value;
jobtitle = document.getElementById("jobTitleRegister").value;
phonenumber = document.getElementById("phone").value;
poolData = {
UserPoolId :<userPoolId>,
'
ClientId : <client id>
};
var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
var attributeList = [];
var dataEmail = {
Name : 'email',
Value : username, //get from form field
};
var dataFirstName = {
Name : 'name',
Value : firstname, //get from form field
};
/*var dataLastName ={
Name : 'family name',
Value : lastname,
};
var dataPhoneNumber ={
Name : 'family name',
Value : lastname,
};*/
var attributeEmail = new AmazonCognitoIdentity.CognitoUserAttribute(dataEmail);
var attributePersonalName = new AmazonCognitoIdentity.CognitoUserAttribute(dataFirstName);
attributeList.push(attributeEmail);
attributeList.push(attributePersonalName);
var temp;
userPool.signUp(username, password, attributeList, null, function(err, result){
if (err) {
alert(err.message || JSON.stringify(err));
return;
}
cognitoUser = result.user;
console.log('user name is ' + cognitoUser.getUsername());
//var cognitoUser = userPool.getCurrentUser();
//console.log('cognitoUser =',cognitoUser);
//change elements of page
//document.getElementById("titleheader").innerHTML = "Check your email for a verification link";
//});
//var userPool1 = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(data);
//console.log('userPool',userPool1);
//var cognitoUser = userPool1.getCurrentUser();
//console.log("temp is ", cognitoUser);
if (cognitoUser != null) {
cognitoUser.getSession(function(err, session) {
if (err) {
console.log(err);
return;
}
console.log('session validity: ' + session.isValid());
console.log('session token: ' + session.getIdToken().getJwtToken());
AWS.config.region = 'us-east-1';
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId : <Identity_Pool>,
Logins : {
// Change the key below according to the specific region your user pool is in.
'cognito-idp.us-east-1.amazonaws.com/${Identity_Pool}' : session.getIdToken().getJwtToken()
}
});
AWS.config.credentials.get(function(err) {
if (!err) {
var id = AWS.config.credentials.identityId;
console.log('Cognito Identity ID '+ id);
// Instantiate aws sdk service objects now that the credentials have been updated
var docClient = new AWS.DynamoDB.DocumentClient({ region: AWS.config.region });
var params = {
TableName: 'TestTable',
Item:{emailId:username, }
};
docClient.put(params, function(err, data) {
if (err)
console.error(err);
else
console.log(data);
});
}
});
});
} else {
console.log(err);
return;
}
});
}
</script>
</body>
</html>
You can use an API for Dynamodb operations with docClient.put()

Required attribute is not working in registration form

I have a register form which works with Vue and local storage, when I submit the form blank or leave out an input the data is going to the local storage the same and not showing the HTML validation which is used by adding required attribute. Is there any way I can fix this problem by showing the HTML validation if the form has inputs which are empty or if the email do not have an at-sign inserted.
Form:
<form id="signup" method="post" v-on:submit.prevent>
<br>
<h1>Registration</h1>
<label for ="studentsorparents">Student or parents:</label>
<input type="text" id="studentsorparents" v-model="studentsorparents" required ="required">
<br><br>
<label for ="username">username:</label>
<input type="text" id="username" v-model="username" required ="required" v-text="null">
<br><br>
<label for="email">email: </label>
<input type="email" id="email" v-model='email' required ="required">
<br><br>
<label for="password">password: </label>
<input type="password" id="password" v-model='password' required ="required">
<br><br>
<button v-on:click='onSubmit' onclick="passuseremail()" >Register</button>
</form>
JS:
var signupApp = new Vue({
el: '#signup',
data: {
studentsorparents: '',
username: '',
email: '',
password: '',
},
methods: {
onSubmit: function () {
// check if the email already exists
var users = '';
var studentParent = this.studentsorparents;
var newUser = this.username;
var newEmail = this.email;
if (localStorage.getItem('users')) { // 'users' is an array of objects
users = JSON.parse(localStorage.getItem('users'));
}
if (users) {
if (users.some(function (user) {
return user.username === newUser
})) {
alert('Account already exits');
return;
}
if (users) {
if (users.some(function (user) {
return user.email === newEmail
})) {
alert('Account already exits');
return;
} else {
alert('Account created');
window.location.href = 'user-profile.html' + '#' + newUser;
}
}
users.push({
'studentsorparents': studentParent,
'username': newUser,
'email': newEmail,
'password': this.password
});
localStorage.setItem('users', JSON.stringify(users));
} else {
users = [{
'studentparents': studentParent,
'username': newUser,
'email': newEmail,
'password': this.password
}];
localStorage.setItem('users', JSON.stringify(users));
}
}
}
});
function passuseremail()
{
var username = document.getElementById('username').value;
localStorage.setItem("user-check", username);
var studentsorparents=document.getElementById('studentsorparents').value;
localStorage.setItem("students-parents-check", studentsorparents)
var email=document.getElementById('email').value;
localStorage.setItem("email-check", email)
return false
}
You need to add button type='submit' to the submit button else it will behave like just any other button.
<button v-on:click='onSubmit' onclick="passuseremail()" type="submit">Register</button>
It then only act as submit button else it will just trigger the button eventlisteners attached.
You have spaces after required attributes in your inputs:
required ="required"
It's incorrect and it will not work; just write it like this:
<input type=email id=email v-model=email required>
You can validate email like this:
const email_re = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+$/;
if (email_re.test( email.value )) {
/* email is valid */
} else {
/* email is not valid */
}
You can add a class to the button like jsValidateRegister.
And the add the code
First declare a variable
isPageValid = true
Then in add the following code for validation so the isPageValid is set to false inside the passuseremail();
$(".jsValidateRegister").click(function ()
{
passuseremail();
});
In the onSubmit: function () check
isPageValid === true

How to send params form web page to parse cloud function?

I make a web form to add some string to database and now my add function is running perfectly but my web does not send params to function when i click submit and console log send undefined to me i dont know what to do please help and thank you
Here my function code and run perfectly
Parse.Cloud.define('addSynonym', function (request, response) {
var SYN = Parse.Object.extend("Synonym");
var CommonwordFromUser = request.params.common_word;
var SynonymwordFromUser = request.params.synonym_word;
console.log(CommonwordFromUser);
console.log(SynonymwordFromUser);
if (CommonwordFromUser == null || SynonymwordFromUser == null) {
response.error("request null values");
} else {
var query = new Parse.Query(SYN)
query.find({
success: function (synResponse) {
var synOBJ = new SYN();
synOBJ.set("common_word", CommonwordFromUser);
synOBJ.set("synonym_word", SynonymwordFromUser);
synOBJ.save(null, {
success: function (success) {
response.success({
"common_word": CommonwordFromUser,
"synonym_word": SynonymwordFromUser
});
},
error: function (error) {
response.error("save failed : " + error.code);
}
});
}
})
}
});
Here my web form my problem
<form id="contact" class="registerForm">
<div class="alert alert-success" id="alertbox">
<strong>Success!</strong> Your Synonym has uploaded.
</div>
<div class="text-center">
<img src="img/icon.png" class="text-center" alt="Responsive image" width="90" height="90">
</div>
<h3 class="text-center font-weight-normal">Welcome to synonym Menu</h3>
<label id="label-tags" for="ask-tags">Common Word :</label>
<fieldset class="form-group">
<input id="common_word" name="common_word" placeholder="Please type some word" type="text" tabindex="1" required>
</fieldset>
<label id="label-tags" for="ask-tags">Synonym Word :</label>
<fieldset class="form-group">
<input id="synonym_word" name="synonym_word" placeholder="Please type some word" type="text" tabindex="2"
required>
</fieldset>
<fieldset class="form-group">
<button name="submit" type="submit" onclick="submitfrom()" id="contact-submit">Submit</button>
</fieldset>
</form>
</div>
<!-- jQuery -->
<script src="js/jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>
<script src="js/standalone/selectize.min.js"></script>
<script src="js/bootstrapValidator.min.js"></script>
<script>
$('.registerForm').bootstrapValidator({
message: 'This value is not valid',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
common_word: {
validators: {
notEmpty: {
message: 'Require !!'
}
}
},
synonym_word: {
validators: {
notEmpty: {
message: 'Require !!'
}
}
},
}
}).on('success.form.bv', function (e) {
submitfrom();
});
$('#alertbox').hide();
function submitfrom() {
var common_word = $('#common_word').val();
var synonym_word = $('#synonym_word').val();
var obj = [{
"common_word": common_word,
"synonym_word": synonym_word,
}];
var data = '{"objects":' + JSON.stringify(obj) + '}';
callParseServerCloudCode("addSynonym", data, function (response) {
if (response) {
console.log(response);
alert("🤖:Ok !");
location.reload();
}
});
$(this).scrollTop(0);
$('.registerForm').data('bootstrapValidator').resetForm();
$('#alertbox').show();
$('#alertbox').fadeTo(2000, 500).slideUp(500, function () {
$('#alertbox').hide();
});
}
function callParseServerCloudCode(methodName, requestMsg, responseMsg) {
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://xxxxxxxxxxxx.herokuapp.com/parse/functions/' + methodName, true);
xhr.setRequestHeader('Content-type', 'application/json');
xhr.setRequestHeader('X-Parse-Application-Id', 'myAppId');
xhr.setRequestHeader('X-Parse-Master-Key', 'myMasterKey');
xhr.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
responseMsg(myArr.result);
}
};
xhr.send(requestMsg);
}
</script>
</body>
</html>
Option 1:
Just change the lines below and it should work
var obj = {
"common_word": common_word,
"synonym_word": synonym_word,
};
var data = JSON.stringify(obj);
Option 2 (recommended):
Install Parse JS SDK: https://docs.parseplatform.org/js/guide/#getting-started
Call cloud code like this:
Parse.Cloud.run(
"addSynonym",
{
"common_word": common_word,
"synonym_word": synonym_word
}
).then(
function() {
console.log('success');
},
function (error) {
console.error(error);
}
);

how to post content using javascript in linkedin

I have to login and post content in linkedin using javascript.
Using below code i have login successfully and when i have posted i got below error in firebug .
NetworkError: 403 Forbidden - https://api.linkedin.com/v1/people/~/mailbox
I need to post content in wall.
what is the issue in below code
<script type="text/javascript" src="http://platform.linkedin.com/in.js">
api_key: xxxxxxx
onLoad: onLinkedInAuth
scope: r_network w_messages
authorize: true
</script>
<script type="text/javascript">
function onLinkedInLoad() {
IN.Event.on(IN, "auth", onLinkedInAuth);
}
function onLinkedInAuth() {
var div = document.getElementById("sendMessageForm");
div.innerHTML = '<h2>Send a Message To Yourself</h2>';
div.innerHTML += '<form action="javascript:SendMessage();">' +
'<input id="message" size="30" value="You are awesome!" type="text">' +
'<input type="submit" value="Send Message!" /></form>';
}
function SendMessage(keywords) {
var message = document.getElementById('message').value;
var BODY = {
"recipients": {
"values": [{
"person": {
"_path": "/people/~",
}
}]
},
"subject": "JSON POST from JSAPI",
"body": message
}
IN.API.Raw("/people/~/mailbox")
.method("POST")
.body(JSON.stringify(BODY))
.result(displayMessageSent)
.error(function error(e) { alert ("No dice") });
}
function displayMessageSent() {
var div = document.getElementById("sendMessageResult");
div.innerHTML += "Yay!";
}
</script>
</head>
<body>
<script type="IN/Login"></script>
<div id="sendMessageForm"></div>
<div id="sendMessageResult"></div>
Using below javascript code I posted linkedin
IN.API.Raw("/people/~/current-status") // Update (PUT) the status
.method("PUT")
.body(JSON.stringify("Test Message"))
.result( function(result) { document.getElementById("statusDiv").innerHTML = "Status updated"; } )
.error( function(error) { /* do nothing */ } );

Categories