问题描述
我有一个 netlify react 应用程序。这是连接到我的github。我正在使用 emailjs 从任何访问我的应用程序的人那里接收消息。
emailjs 处理三个 id 'SERVICE_ID'、'TEMPLATE_ID' 和 'USER_ID'。但我不想在我的组件 js 文件中公开使用它们。
驱动功能
function sendEmail(e) {
e.preventDefault(); //This is important,i'm not sure why,but the email won't send without it
emailjs.sendForm(SERVICE_ID,TEMPLATE_ID,e.target,USER_ID)
.then((result) => {
window.location.reload() //This is if you still want the page to reload (since e.preventDefault() cancelled that behavior)
},(error) => {
console.log(error.text);
});
}
解决方法
我认为您指的是环境变量,为了在本地进行测试,它会因您用于创建应用程序的堆栈而异,如果您使用 react create app,您可以在根目录中创建一个 .env 文件您的项目并填充值
REACT_APP_SERVICE_ID ="your_value"
REACT_APP_TEMPLATE_ID ="your_value"
REACT_APP_USER_ID ="your_value"
不要忘记从 git 中排除这个文件,以避免在你的 repo 中推送秘密。要做到这一点,将此添加到您的 .gitignore
.env
之后,您可以像这样使用 process.env 调用代码中的变量:
process.env.REACT_APP_SERVICE_ID
现在修改代码:
function sendEmail(e) {
// Your code
emailjs.sendForm(process.env.REACT_APP_SERVICE_ID,process.env.REACT_APP_TEMPLATE_ID,e.target,process.env.REACT_APP_USER_ID)
// your promise
}
要在 netlify 中运行,您必须在 netlify 项目中添加变量,请按照以下部分操作:https://docs.netlify.com/configure-builds/environment-variables/#declare-variables
正如你所指出的,我添加了前缀 REACT_APP_,这是因为 react create app 是这样做的:
注意:您必须创建以开头的自定义环境变量 REACT_APP_。除了 NODE_ENV 之外的任何其他变量都将被忽略 避免意外暴露机器上的私钥,这可能会 同名。更改任何环境变量都需要 如果开发服务器正在运行,请重新启动它。
如果您使用 gatsby 或 nextjs,env 变量命名约定可能会改变,因此请注意这一点。
,检查Adding env variables to react app
您可以在根目录中创建一个 .env
并在其中添加您的密钥、api 端点等。
您可以在 netlify 上设置 env 变量。请检查以下图片。