I am not well-versed in Node.js, react, etc and have the following issue:
I have a function that is called on submit from a form on a webpage that looks like this (I have omitted some details for privacy purposes):
class Email extends React.Component{
constructor(props){
super(props);
this.state = {
subject: "",
message: ""
};
}
handleUpdateSubjectLine(evt){
this.setState({ subject: evt.target.value});
}
handleUpdateMessageBox(evt){
this.setState({ message: evt.target.value});
}
async handle_email(evt){
var sgMail = require('@sendgrid/mail');
var subject = this.state.subject;
var message = this.state.message;
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
console.log("subject txt: " + subject);
console.log("msg txt: " + message);
var msg = {
to: 'OMMITED',
from: 'OMMITED',
subject: subject,
text: message,
};
sgMail.send(msg).catch(err =>{
console.log(err);
});
console.log("Message Allegedly Sent!");
}
When checking my inbox for the test email produced by the above form, not only do I not see any email, the web browser would give the following messages:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.sendgrid.com/v3/mail/send. (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘https://sendgrid.api-docs.io’).
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.sendgrid.com/v3/mail/send. (Reason: CORS request did not succeed).
I have cors and @sendgrid/mail installed from npm and can't seem to figure out how to apply the above to this api call despite watching others implement it on YouTube.
Thanks!
Sending directly from a browser frontend (React) app is not allowed. (CORS will block the request.) You need to create a Node.js server (I use Next JS) and handle the sending of email (via SendGrid API) from your server. Here are two really good tutorials on how to handle this:
Using SendGrid:
https://docs-git-success-185-add-nextjs-sengrid-guide.zeit.now.sh/guides/deploying-nextjs-nodejs-and-sendgrid-with-zeit-now
Using Nodemailer:
https://medium.com/the-couch/adding-a-contact-form-to-your-next-js-app-7a1b5f63f27
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With