简体   繁体   中英

Sendgrid and AWS Lambda Serverless Form

I am trying to set up a super basic email form using Sendgrid and AWS Lambda. I am having problems sending data from the form to the Lambda function. The error I get is "Unexpected token u in JSON at position 0". I know it is something to do with how I am sending the body. Below is my code for my Lambda function.

require("dotenv").config();
const sendgrid = require('@sendgrid/mail');

exports.handler = (event, context, callback) => {
sendgrid.setApiKey(process.env.SENDGRID_API_KEY);
var data = JSON.parse(event.body);
const msg = {
    to: data.to,
    from: 'test@gmail.com',
    subject: data.subject,
    text: data.message,
};
sendgrid.send(msg);
callback(null, 'Message Sent');
}

Here is the Javascript for my form.

$(document).ready(function() {

$("#submit").click(function(e) {
    e.preventDefault();

    var to = $("#to").val();
    var subject = $("#subject").val();
    var message = $("#message").val();

    var data = {
        'to': to,
        'subject': subject,
        'message': message
    }

    $.ajax({
        type: "POST",
        url: 'https://xxxxxxxx.execute-api.us-east-1.amazonaws.com/prod/xxxxx',
        contentType: 'application/json',
        data: JSON.stringify({data}),
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        success: function(res){
            console.log('Email was sent.');
        },
        error: function(){
            console.log('Error.');
        }
    });

})

});

Thanks!

The problem is you are trying to parse a JSON object, not a string.

var data = JSON.parse(event.body);

This is not correct. Just assign,

var data = event.body;

It should take care from there.

Hope it helps.

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