通过Firebase功能发送电子邮件时出现Firebase SendGrid错误-错误:请求错误

时间:2019-09-10 09:15:29

标签: firebase google-cloud-functions sendgrid

我正在使用Firebase和SendGrid,并且正在使用Firebase函数。创建新用户时,我正在尝试发送电子邮件。触发函数时,出现以下错误:

 firestoreEmail: Function execution started
2019-09-10T08:13:49.245Z I firestoreEmail: { 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: 'Tue, 10 Sep 2019 08:13:49 GMT',
        'content-type': 'application/json',
        'content-length': '365',
        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] } } } 

这是我的Index.js:

 const functions = require('firebase-functions');

const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);


const SENDGRID_API_KEY = 'exact API key here because functions.config().sendgrid.key doesn't work, says sendgrid is undefined';

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

exports.firestoreEmail = functions.firestore
.document('Users/{userId}/Followers/{followerId}')
.onCreate(event => {

    const userId = "for now exact id";

    const db = admin.firestore()

    return db.collection('Users').doc(userId)
            .get()
            .then(doc => {
                const user = doc.data()

                const msg = {
                    to: "someEmailAddress@gmail.com",
                    from: 'hello@someEmailAddress.com',
                    subject: 'New Follower',
                };

                return sgMail.send(msg)
            })
            .then( () => console.log('email sent!') )
            .catch( (err) => console.log(err) )
}) 

P.S。我正在关注Fireship的教程https://www.youtube.com/watch?v=JVy0JpCOuNI&t=333s

编辑: 这些是数据库SC first image second image

1 个答案:

答案 0 :(得分:0)

问题是const msg缺少templateId字段,如果使用SendGrid,则这显然是必需的。 这是有效的代码段:

// "chart" component
export class Chart implements AfterViewInit {

   @Input() widget:Chart;

   /**
     * After view is inited
     * Now I know that HTML element is in DOM
     */
    ngAfterViewInit() {
        this.createChart();
    }
}