0

I have a Hugo site running on Netlify with Mailgun-js for a couple of forms.

I try and run a simple contact function in Netlify but get a JSON related error

Jun 24, 12:57:15 PM: 7af5f746 ERROR Invoke Error {"errorType":"SyntaxError","errorMessage":"Unexpected end of JSON input","stack":["SyntaxError: Unexpected end of JSON input"," at JSON.parse ()"," at Runtime.exports.handler (/var/task/functions/contact/contact.js:11:19)"," at Runtime.handleOnceNonStreaming (/var/runtime/Runtime.js:73:25)"]}

if I remove the JSON.parse I get the following:

{"errorType":"SyntaxError","errorMessage":"Unexpected token b in JSON at position 0","trace":["JSON.parse ()","t.handler

I am at a total loss to understand how and where to debug this :(

This is the code which used to work:

require('dotenv').config()

const { MAILGUN_API_KEY, MAILGUN_DOMAIN, MAILGUN_URL, FROM_EMAIL_ADDRESS, CONTACT_TO_EMAIL_ADDRESS } = process.env

const mailgun = require('mailgun-js')({ apiKey: MAILGUN_API_KEY, domain: MAILGUN_DOMAIN, host: "api.eu.mailgun.net" })

exports.handler = async (event, context, callback) => {

    /* the server-side functionality */

    const data = JSON.parse(event.body) 

    var text = `Dear ${data.name}, \n\n`
    text += `${data.message} \n`
    text += `Country of residence: ${data.country} \n`  

    const style = "<style> </style>"
    var body = `<html>${style}<div>`
    body += `<p>Dear ${data.name},</p>`
    body += `<h4>Your message:</h4><p>${data.message}</p>`
    body += `<p>Country of residence: ${data.country}</p>`
    body += `</div></html>`

    let response
    try {
        response = await mailgun.messages().send({
            to: data.email,
            bcc: CONTACT_TO_EMAIL_ADDRESS,
            from: FROM_EMAIL_ADDRESS,
            subject: `Enquiry for Summertime from ${data.arrdate}`,
            text: text,
            html: body
        })
    } 
    catch (error) {
        console.log('Error: ', error)
        return {
            statusCode: error.statusCode || 500,
            headers: { "Access-Control-Allow-Origin": "*" },
            body: JSON.stringify({  error: error.message })
        }
    }

    return {
        statusCode: 200,
        headers: { "Access-Control-Allow-Origin": "*" },
        body: JSON.stringify({ result: 200  })
    }
}```
  • Did you try to log out your event.body? The error most likely means that the body you're sending is not a valid JSON. – Hrishikesh Kokate Jun 25 '22 at 16:45
  • I just submit the form (and receive the sumitted details by mail). Am I meant to do more than that to get the function to work? It now works locally ok but not on Netlify. – Our Man in India Jun 27 '22 at 13:16

0 Answers0