I'm building a form on a website with Gatsby, sendgrid, and Google reCAPTCHA. I've used this same code with other websites and it works fine. Also when the async function validateHuman(token) is commented out the code works fine and the email is sent. The problem is when I add it back, which I need for spam protection etc I'm getting the error below:
This is my code for the API using gatsby functions (nodejs):
import fetch from "node-fetch"
// using gatsby example with dynamic data
const sendgrid = require("@sendgrid/mail")
//Your API Key from Sendgrid
sendgrid.setApiKey(process.env.SENDGRID_API_KEY)
const message = {
//Your authorized email from SendGrid
from: process.env.SENDGRID_AUTHORIZED_EMAIL,
}
//so without this seciton and node-fetch it works
async function validateHuman(token){
console.log("validate human running")
const secret = process.env.RECAPTCHA_KEY;
const response = await fetch(`https://www.google.com/recaptcha/api/siteverify?secret=${secret}&response=${token}`,
{
method: "POST",
}
)
//this is where It's failing??
const data = await response.json();
return data.success;
}
//main function
export default async(req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*');
console.log("This is where the req should be logging")
// console.log(req.body);
//this is where I'm getting response error, validate token function above
const human = await validateHuman(req.body.token);
// const human = true;
if (!human){
console.log("this message shows we're getting to the !human part")
res.status(400);
res.json({errors: ["Please, you're not fooling us, bot."]})
return;
}
try {
if (req.method !== "POST") {
res.json({ message: "Try a POST!" })
}
if (req.body) {
console.log(req.body)
let spam = "";
if(req.body.Fax || req.body.NZ){
spam = " (spam)"
}
message.to = process.env.SENDGRID_AUTHORIZED_EMAIL
message.subject = "Glacier support form submission from "+ req.body.name + spam
message.text = "Name: " + req.body.name + " Phone: " + req.body.phone + " Email: " + req.body.email + " Message: " + req.body.message
message.html = "Name: " + req.body.name + "<br/>" + " Phone: " + req.body.phone + "<br/>" + " Email: " + req.body.email + "<br/>" + "<br/>" + " Message: " + req.body.message
}
return sendgrid.send(message).then(
() => {
res.status(200).json({
message: "I will send email",
})
},
error => {
console.error(error)
if (error.response) {
return res.status(500).json({
error: error.response,
})
}
}
)
} catch (err) {
console.log(err)
return res.status(500).json({ message: "There was an error", error: err })
}
}
I've tried clearing cache and reinstalling dependencies and commented out enough to know where the issue is but I'm not sure why it's happening when the code works with other projects. The only difference I can see is that I also have a typescript api with this project but I don't think that should have any effect? Any help or suggestions would be appreciated!

