【发布时间】:2019-10-15 23:36:50
【问题描述】:
我正在尝试使用我的 Vue/Nuxt 应用程序设置 SendGrid,但是我只能通过对 API 密钥进行硬编码来使其工作。当我尝试使用首选的环境变量方法时,我得到一个未经授权的错误。这是因为应用程序没有获取变量,而是返回 Undefined。
如何让应用获取变量?
我的 API KEY 保存在项目根目录中名为 sendgrid.env 的文件中。
然后,我的 Nuxt 项目中运行了一个 Node/Express 应用程序,代码如下:
const express = require('express')
const app = express()
app.get('/', (req, res, next) => {
res.send('API root')
})
app.get('/sendmail', (req, res, next) => {
// using Twilio SendGrid's v3 Node.js Library
// https://github.com/sendgrid/sendgrid-nodejs
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
to: 'somebody@something.net',
from: 'no-reply@somewhereelse.com',
subject: 'Test SendGrid',
text: 'This is a test of the SendGrid app on Node',
html: '<strong>This is a test of the SendGrid app on Node</strong>',
};
sgMail.send(msg);
res.send('SendMail API');
})
// export the server middleware
module.exports = {
path: '/api',
handler: app
}
我已经使用 Curl 和硬编码 API 密钥测试了代码,所以密钥是正确的,它只是没有被拾取的环境变量。
我做错了什么?
【问题讨论】:
标签: node.js express vue.js sendgrid nuxt.js