I'm just trying to get a simple example from the SendGrid docs working. This section of code is called from my Node.js + Express application:
function sendConfirmationEmail() {
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
to: 'my@email.com', // Change to your recipient
from: 'verifiedsender@gmail.com', // Change to your verified sender
subject: 'Hello, world!',
text: 'Thank you for your interest. We will let you know if we need any more information.',
html: '<strong>Thank you for your interest. We will let you know if we need any more information.</strong>',
};
sgMail
.send(msg)
.then(() => {
console.log('Email sent')
})
.catch((error) => {
console.error(error)
});
}
Seeing this logged:
> { Error: Forbidden
at axios.then.catch.error (node_modules/@sendgrid/client/src/classes/client.js:146:29)
at process._tickCallback (internal/process/next_tick.js:68:7)
code: 403,
message: 'Forbidden',
response:
{ headers:
{ server: 'nginx',
date: 'Sat, 27 Feb 2021 15:58:48 GMT',
'content-type': 'application/json',
'content-length': '281',
connection: 'close',
'access-control-allow-origin': 'https://sendgrid.api-docs.io',
'access-control-allow-methods': 'POST',
'access-control-allow-headers': 'Authorization, Content-Type, On-behalf-of, x-sg-elas-acl',
'access-control-max-age': '600',
'x-no-cors-reason': 'https://sendgrid.com/docs/Classroom/Basics/API/cors.html' },
body: { errors: [Array] } } }
Not sure why this is a CORS error, as it is not happening in the browser. Any ideas?
The suggested workaround from SendGrid is not helpful:
You can create a server-based application, which will protect your API keys from being released to the world. Languages like NodeJS, PHP, Ruby, Python, C#, Go, and Java, and others can be implemented to make calls to the API from the security of a locked down server environment.