I'm trying to set up a form that sends info to my email using sendgrid and Gatsby Functions. I've tried following the gatsby sendgrid example, and the youtube video "four real world solutions using gatsby functions..." but with both I end up getting a authorization/CORS error:
*console error
*response.body.errors
*verified single sender
I've tried a few things like:
- adding cors middleware around my function (although I wasn't 100% I did this right)
- setting
res.set({"Content-Type": "application/json" Authorization: `Bearer ${process.env.SENDGRID_API_KEY}` });
- setting
res.setHeader('Access-Control-Allow-Origin', '*')
- creating new api keys
- testing gatsby develop & build, clearing cache etc
I'm running out of ideas so any advice would be appreciated :)
code for current form and api is below:
src/api/sendgrid.js
const sgMail = require('@sendgrid/mail')
console.log("api key:" + process.env.SENDGRID_API_KEY, process.env.SENDGRID_AUTHORIZED_EMAIL)
sgMail.setApiKey(process.env.SENDGRID_API_KEY)
export default async (req, res) => {
res.set({"Content-Type": "application/json",
Authorization: `Bearer ${process.env.SENDGRID_API_KEY}`
});
const msg = {
to: 'myemail@gmail.com', // Change to your recipient
from: process.env.SENDGRID_AUTHORIZED_EMAIL, // Change to your verified sender
subject: 'Sending with SendGrid is Fun',
text: 'and easy to do anywhere, even with Node.js',
html: '<strong>and easy to do anywhere, even with Node.js</strong>',
}
sgMail
.send(msg)
.then(() => {
console.log('Email sent'); console.log(msg);
})
.catch((error) => {
console.error(error);console.log('there was an error');
return res.status(500).json({
error: error.response,
})
})
return res.status(200)
}
src/pages/components/contact.js
const Contact = () => {
const [serverState, setServerState] = useState({
formSent: false,
});
const {
register,
handleSubmit,
formState: { errors },
} = useForm()
const onSubmit = data => {
fetch(`/api/sendgrid`, {
method: `POST`,
body: JSON.stringify(data),
headers: {
"content-type": `application/json`,
},
})
.then(res => res.json())
.then(body => {
console.log(`response from API:`, body);
})
}
console.log({ errors })
return(
<div style={{ display: "grid", width: "100%", }} id="contactSection" >
<div
style={{
// By using the same grid area for both, they are stacked on top of each other
gridArea: "1/1",
position: "relative",
// This centers the other elements inside the hero component
placeItems: "center",
display: "grid",
width: "100%",
}}
>
<ContactDiv>
{/* class={serverState.formSent ? "sent" : ""} */}
<span
// css={styles(serverState.formSent)}
>
<h1>Message Sent</h1>
<p>I'll be in touch shortly. Regards, Daniel.</p>
</span>
{/* <MobileId id="contactM"/> */}
<h1 id="contactM">Need a Website?</h1>
<ContactInfo>
<p>For a free project consultation call, email or use the form below.</p>
<p>Mobile:<br/> 022 078 0868</p>
<p>Email:<br/> daniel@thoughtfulhq.com</p>
</ContactInfo>
<div>
<form
onSubmit={handleSubmit(onSubmit)}
// action="/api/sendgrid" method="POST"
>
<label htmlFor="name">
<p>Name:</p>
<input
type="text"
name="name"
required
{...register("Name", { required: true, maxLength: 100 })}
/>
</label>
<label htmlFor="email">
<p>Email:</p>
<input
type="email"
name="email"
required
{...register("Email", { required: true, pattern: /^\S+@\S+$/i })}
/>
</label>
<label htmlFor="message">
<p>Project Details:</p>
<textarea
name="message"
id="message"
rows="5"
required
{...register("Message", { required: true, maxLength: 2000 })}
/>
</label>
<button type="submit">Submit</button>
</form>
</div>
</ContactDiv>
</div>
</div>
)
}
export default Contact;