I have a Firebase cloud function called needCode that sends an email using sendgrid. However, I always get a Bad Request.
import * as sgMail from '@sendgrid/mail'
sgMail.setApiKey(SENDGRID_API_KEY);
export const needCode = functions.https.onCall((data, context) => {
const { email, name, message } = data
return new Promise(function (resolve, reject) {
const msg = {
to: '[email protected]',
from: email,
templateId: 'd-ac6fdd2f3ee746fc94d211ad947a8d0e',
dynamic_template_data: {
name: name,
message: message
}
}
return sgMail.send(msg)
.then(() => {
resolve(
{ message: "Email sent" }
);
}).catch(error => {
console.log(error)
reject(
new HttpsError('unknown', 'Error sending email')
);
});
});
})
{ Error: Bad Request
at Request.http [as _callback] (node_modules/@sendgrid/client/src/classes/client.js:124:25)
at Request.self.callback (node_modules/request/request.js:185:22)
at emitTwo (events.js:126:13)
at Request.emit (events.js:214:7)
at Request.<anonymous> (node_modules/request/request.js:1161:10)
at emitOne (events.js:116:13)
at Request.emit (events.js:211:7)
at IncomingMessage.<anonymous> (node_modules/request/request.js:1083:12)
at Object.onceWrapper (events.js:313:30)
at emitNone (events.js:111:20)
code: 400,
message: 'Bad Request',
response:
{ headers:
{ server: 'nginx',
date: 'Sat, 14 Mar 2020 04:09:13 GMT',
'content-type': 'application/json',
'content-length': '402',
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] } } }
Probably need a paid firebase account to allow external network calls. Recommend checking the error details:
console.log(error.response.body)
I have the exact same issue and error, same setup. Has anyone got a solution?
I have some other projects using the exact same setup and they don't seem to have an issue.
@teanz Have you tried my comment above?
Since the others haven't responded, I'll chime in that I found my way here with the same error and what childish-sambino suggested worked perfectly. The error messages in the HTTP response are actually really good. In my case I had a trailing space on my template ID. Just to be thorough, here is the full code snippet that solved this problem for me:
sgMail.send(msg).catch(err => {
console.log(err);
console.log(err.response.body)
});;
I've updated the docs in a few places to better indicate how to handle/log error responses: https://github.com/sendgrid/sendgrid-nodejs/commit/0e8c2761fb8d0beeac8107d0d963bb6ab80b0a6d
Thanks, logging the error out further gave me the real cause... not having my sender identity setup -_- Appreciate the help.
Most helpful comment
Probably need a paid firebase account to allow external network calls. Recommend checking the error details: