我有一个Next js应用程序,它有一个联系人表单。我正在使用Emailjs向我的gmail帐户发送电子邮件。这在开发中非常有效,但一旦我部署它,它就停止了工作,它给了我这样的信息:
取消捕获用户ID是必需的。参观https://dashboard.emailjs.com/admin/integration
这是我的代码(与emailjs-web中的示例基本相同(
const [result, setResult] = useState(false);
const form = useRef();
const sendEmail = (e) => {
e.preventDefault();
emailjs
.sendForm(
process.env.EMAIL_SERVICE,
process.env.EMAIL_TEMPLATE,
form.current,
process.env.EMAIL_USER
)
.then(
(result) => {
console.log(result.text);
},
(error) => {
console.log(error.text);
}
);
e.target.reset();
setResult(true);
};
//THIS CODE IS JUST TO ERASE THE "SENT" MESSAGE AFTER 5 secs
setTimeout(() => {
setResult(false);
}, 5000);
我使用.env文件来获得实际值,正如我所说,它在开发中非常有效。
我是不是错过了让它在生产中发挥作用的东西?
我在使用NextJS时也遇到了这个问题。在我的例子中,我在.env.local
文件中的变量前面加了NEXT_PUBLIC_
,然后它就像一个符咒。
例如,NEXT_PUBLIC_EMAIL_SERVICE_ID
而不是EMAIL_SERVICE_ID
。
PS:更改.env.local
文件后,请记住重新启动服务器。
注销环境变量。它们很可能在生产中未定义。NextJS环境变量文档
文档示例-next.config.js
:内部
const {
PHASE_DEVELOPMENT_SERVER,
PHASE_PRODUCTION_BUILD,
} = require('next/constants')
// This uses phases as outlined here: https://nextjs.org/docs/#custom-configuration
module.exports = (phase) => {
// when started in development mode `next dev` or `npm run dev` regardless of the value of STAGING environmental variable
const isDev = phase === PHASE_DEVELOPMENT_SERVER
// when `next build` or `npm run build` is used
const isProd = phase === PHASE_PRODUCTION_BUILD && process.env.STAGING !== '1'
// when `next build` or `npm run build` is used
const isStaging =
phase === PHASE_PRODUCTION_BUILD && process.env.STAGING === '1'
console.log(`isDev:${isDev} isProd:${isProd} isStaging:${isStaging}`)
const env = {
RESTURL_SPEAKERS: (() => {
if (isDev) return 'http://localhost:4000/speakers'
if (isProd) {
return 'https://www.siliconvalley-codecamp.com/rest/speakers/ps'
}
if (isStaging) return 'http://localhost:11639'
return 'RESTURL_SPEAKERS:not (isDev,isProd && !isStaging,isProd && isStaging)'
})(),
RESTURL_SESSIONS: (() => {
if (isDev) return 'http://localhost:4000/sessions'
if (isProd) return 'https://www.siliconvalley-codecamp.com/rest/sessions'
if (isStaging) return 'http://localhost:11639'
return 'RESTURL_SESSIONS:not (isDev,isProd && !isStaging,isProd && isStaging)'
})(),
}
// next.config.js object
return {
env,
}
}
我目前在EmailJS的密钥方面遇到了类似的问题,我找到了Emile的这个答案,这帮助我了解了更多。