谷歌云功能-SendGrid-400错误请求



我正在尝试使用谷歌云功能中的SendGrid发送电子邮件。我在Firebase环境变量中有我的密钥,所以这是存在的。

const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(SENDGRID_API_KEY);

这是我的GCF.ts代码:

代码

const msg = {
to: to,
from: from,
subject: 'Email Subject',
content: [{
type: "text/html",
value: body
}]
};
await sgMail.send(msg)
.then(r => {
console.log(r);
});

当我触发该功能并检查日志时,这就是我得到的错误:

错误

error:  { Error: Bad Request
at ResponseError (node_modules/@sendgrid/mail/node_modules/@sendgrid/helpers/classes/response-error.js:19:5)
at Request.http [as _callback] (node_modules/@sendgrid/mail/node_modules/@sendgrid/client/src/classes/client.js:124:25)
at Request.self.callback (node_modules/@sendgrid/mail/node_modules/request/request.js:185:22)
at emitTwo (events.js:106:13)
at Request.emit (events.js:191:7)
at Request.<anonymous> (node_modules/@sendgrid/mail/node_modules/request/request.js:1161:10)
at emitOne (events.js:96:13)
at Request.emit (events.js:188:7)
at IncomingMessage.<anonymous> (node_modules/@sendgrid/mail/node_modules/request/request.js:1083:12)
at IncomingMessage.g (events.js:292:16)
code: 400,
message: 'Bad Request',
response: 
{ headers: 
{ server: 'nginx',
date: 'Sun, 16 Dec 2018 16:27:56 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: [Object] } } }

有人熟悉这个错误吗?它提到了CORS,但这毫无意义,因为它是一个云功能,而不是浏览器。SendGrid API并不是很好,它主要介绍了字段名称,没有提供任何示例。感谢您提供的任何帮助!

编辑

只是为了更新这个问题,在我发给自己的前端响应中,我发现了一个与GCF日志中的console.log(error)不同的错误:

"Email failed: Bad Request (400)
The from object must be provided for every email send. 
It is an object that requires the email parameter, 
but may also contain a name 
parameter.  e.g. {"email" : "example@example.com"}  or 
{"email" : "example@example.com", "name" : "Example Recipient"}.
from.email
http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#message.from"

第2版:解决方案

我的发件人电子邮件来源来自Firestore中的一个文档,我试图获取一个不存在的字段,因为我查询了错误的文档,因此fromundefined。更正了它,并根据下面的建议/答案删除了msg对象中的"内容",一切都很好。

根据文档。。。msg有错误的元素:

const sg = require('@sendgrid/mail');
sg.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
to: 'test@example.com',
from: 'test@example.com',
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>',
};
sg.send(msg).then(() => {
/* assume success */
})
.catch(error => {
/* log friendly error */
console.error(error.toString());
/* extract error message */
const {message, code, response} = error;
/* extract response message */
const {headers, body} = response;
});

相关内容

  • 没有找到相关文章

最新更新