Javascript Firebase函数环境变量无法读取未定义的属性
我有一个与firebase连接的angular应用程序。到目前为止,我已经让数据库和身份验证工作。但现在我被困在云功能上。 每次有人预订福利时,我都会尝试向NodeEmailer发送一封电子邮件。 函数代码主要是从firebase github函数示例中复制的 像这样:Javascript Firebase函数环境变量无法读取未定义的属性,javascript,angular,firebase,google-cloud-functions,Javascript,Angular,Firebase,Google Cloud Functions,我有一个与firebase连接的angular应用程序。到目前为止,我已经让数据库和身份验证工作。但现在我被困在云功能上。 每次有人预订福利时,我都会尝试向NodeEmailer发送一封电子邮件。 函数代码主要是从firebase github函数示例中复制的 像这样: 'use strict'; const functions = require('firebase-functions'); const nodemailer = require('nodemailer'); // Confi
'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;
});
firebase functions:config:set gmail.email="myusername@gmail.com" gmail.password="secretpassword"
使用firebase Service时,我将函数部署到firebase,但出现错误:
-TypeError:无法读取未定义的属性“email”
当我检查firebase函数:config:get时,它会显示正确的数据
webapp本身还没有部署(可能是这样吗?)
如有任何想法/帮助,将不胜感激
thx如果您希望使用firebase serve对函数进行本地模拟,以拾取环境变量,则需要按照以下指令进行操作: 如果使用自定义函数配置变量,请运行 之前,请在项目的函数目录中执行以下命令 火箭筒发球
firebase functions:config:get > .runtimeconfig.json
但是,如果您使用的是Windows PowerShell,请替换上述命令
与:
为什么不使用
函数
目录中的.env
文件?它会自动捕捉环境变量。thx,我不知道。第一次尝试用firebase:p创建一个网站,这个答案缺少一个重要的注意事项:在functions目录中运行这个。感谢您测试.env
以实现通用性,即使在部署到站点之后也是如此,还是您的意思是仅将其用于本地测试?因为如果是后一种方法,Doug的答案会更好,因为它将使用您可以在函数中使用的实际环境配置,而不必使用两种不同的方法。一般来说,也用于生产。基于…Doug的答案()。谢谢,这澄清了它,虽然“官方”方式是使用firebase的函数配置,有文档记录,有支持,所以通过.env
使用它可能更实用,我想说…好的观点@benomatis,谢谢。
firebase functions:config:get | ac .runtimeconfig.json