Firebase函数环境变量无法读取未定义的属性

Bob*_*ers 1 firebase google-cloud-functions angular

我有一个与firebase连接的有角度的应用程序。到目前为止,我已经完成了数据库和身份验证。但是现在,我只能使用云功能。每当有人预订受益人时,我都会尝试通过nodemailer发送电子邮件。该功能代码大部分是从firebase github函数示例中复制的,如下所示:

'use strict';

const functions = require('firebase-functions');
const nodemailer = require('nodemailer');
// Configure the email transport using the default SMTP transport and a GMail account.
// For other types of transports such as Sendgrid see https://nodemailer.com/transports/
// TODO: Configure the `gmail.email` and `gmail.password` Google Cloud environment variables.
const gmailEmail = functions.config().gmail.email;
const gmailPassword = functions.config().gmail.password;
const mailTransport = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: gmailEmail,
    pass: gmailPassword,
  },
});

// Sends an email confirmation when a user changes his mailing list subscription.
exports.sendEmailConfirmation = functions.database.ref('/users/{uid}').onWrite(async (change) => {
  const snapshot = change.after;
  const val = snapshot.val();

  if (!snapshot.changed('subscribedToMailingList')) {
    return null;
  }

  const mailOptions = {
    from: '"Spammy Corp." <noreply@firebase.com>',
    to: val.email,
  };

  const subscribed = val.subscribedToMailingList;

  // Building Email message.
  mailOptions.subject = subscribed ? 'Thanks and Welcome!' : 'Sad to see you go :`(';
  mailOptions.text = subscribed ?
      'Thanks you for subscribing to our newsletter. You will receive our next weekly newsletter.' :
      'I hereby confirm that I will stop sending you the newsletter.';

  try {
    await mailTransport.sendMail(mailOptions);
    console.log(`New ${subscribed ? '' : 'un'}subscription confirmation email sent to:`, val.email);
  } catch(error) {
    console.error('There was an error while sending the email:', error);
  }
  return null;
});
Run Code Online (Sandbox Code Playgroud)

之后,我将环境变量设置如下:

firebase functions:config:set gmail.email="myusername@gmail.com" gmail.password="secretpassword"
Run Code Online (Sandbox Code Playgroud)

使用firebase服务时,我将函数部署到firebase时出现错误:-TypeError:无法读取未定义的属性“ email”

当我使用firebase functions:config:get进行检查时,它向我显示了正确的数据Webapp本身尚未部署(可以吗?)

任何想法/帮助将不胜感激

Dou*_*son 6

如果要使用本地仿真功能firebase serve来拾取环境变量,则需要遵循文档中的以下说明

如果您使用的是自定义函数配置变量,请在运行firebase serve之前在项目的functions目录中运行以下命令。

firebase functions:config:get > .runtimeconfig.json
Run Code Online (Sandbox Code Playgroud)

但是,如果您使用的是Windows PowerShell,则将上述命令替换为:

firebase functions:config:get | ac .runtimeconfig.json
Run Code Online (Sandbox Code Playgroud)

  • 这个答案缺少一个重要的说明,使这项工作有效:*在函数目录中运行它*。谢谢 (2认同)