Direkt zum Inhalt

Why is JSON.parse(event.body) returning null despite form input?

0

I'm trying to get values being passed into a form to themselves be passed to my lambda function backend.

The first roadblock I encountered on this project was that the event instance that is passed as a parameter to my handler was empty. That is, when I would try and log the event instance, the event would come back empty.

As a rough example, this code:

 module.exports.handler = (event, context, callback) => {console.log(event);}

would return "{}."

After some research, I learned that the reason the event instance would come back as empty, is because I had failed to check the lambda proxy integration option at the "Integration Requests" page on the API's Resource/Method page.

So, I enabled lambda proxy integration, and it sort of worked. the event instance is no longer empty; It doesn't return "{}." anymore.

However, although the event instance is now full of information, the properties/values I'm trying to recover from the event instance are now null, specifically body.

So, although event is no longer empty, JSON.parse(event.body); returns null

I don't understand where or why the values being passed into the form are being lost when transmitted to my lambda function backend.

You can see Cloudwatch logs yourselves here:

https://i.stack.imgur.com/p6f2q.png

Also, here is the handler and front-end codes, respectively.

const AWS = require('aws-sdk');
const validator = require("validator");

module.exports.handler = function(event, context, callback) {
  var response = {
    statusCode:200,
    headers:{
      "Access-Control-Allow-Origin": "*",
      'Access-Control-Allow-Credentials':"true",
      "Content-Type":"application/json"
    },
    body: JSON.stringify({"body":event})
  }
  console.log(response);
  console.log(context);
  try{
    console.log("inside the try loop", null, 2);
    console.log("before parsing the json from the post method", null, 2);
    console.log(event);
    var data = JSON.parse(event.body);
    console.log(data);
    console.log("after parsing the json from the post method", null, 2);
    var email = data.email;
    var comment = data.comment;
    if(validator.isEmail(email) == "false" || validator.isEmpty(comment) == "false"){
      callback(new Error("The email or comment were defectous."));
      return;
    }
    email = validator.escape(email);
    comment = validator.escape(comment);
    callback(null, response);
    return;

  } catch(error){
    console.log("inside the error loop", null, 2);
    console.log(error);
    console.log(error.description);
    callback(null, response);
    return;
  }

};
$(function(){
    $('.contactForm').submit(function(event){
        event.preventDefault();
        console.log("Submit event is fired");
        var data = {
          email: getEmail(),
          comment: getComment()
        };
        $.ajax({
          url: "SOMEURL",
          type: 'post',
          contentType: "application/json",
          body: JSON.stringify(data),
          success: function(){
            console.log("Lambda Function successully invoked.");
            console.log(data);
            $('.btn').attr('disabled', true);
            $('#emailFormInput').val('');
            $('#commentFormInput').val('');
          },
          error: function(jqXHR, textStatus, errorThrown){
            if (jqXHR.status == 500) {
                      console.log('Internal error: ' + jqXHR.responseText+"  "+errorThrown);
                  } else {
                      console.log(errorThrown);
                  }
          }
        });
    });
  });
gefragt vor 5 Jahren5852 Aufrufe
1 Antwort
0

I didn't read through your log, but I guess it is similar to the problem I encountered before. You can try to wrap the thing using an if statement, ie. if(event.body).

You can find more details in the following tutorial.
https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-create-api-as-simple-proxy-for-lambda.html .

beantwortet vor 5 Jahren

Du bist nicht angemeldet. Anmelden um eine Antwort zu veröffentlichen.

Eine gute Antwort beantwortet die Frage klar, gibt konstruktives Feedback und fördert die berufliche Weiterentwicklung des Fragenstellers.