【问题标题】:Error: Cannot find module 'sendgrid' when using sendgrid错误:使用 sendgrid 时找不到模块“sendgrid”
【发布时间】:2020-11-09 08:17:18
【问题描述】:

尝试执行我的代码时,我不断收到“错误:在控制台中找不到模块“sendgrid”。我之前没用过sendgrid,是不是我做错了什么?

 SENDGRID =
  "<key>";

const sgMail = require("sendgrid").SendGrid(conf);
sgMail.setApiKey(process.env.SENDGRID);

const msg = {
  to: "eden.cmo@gmail.com", // Change to your recipient
  from: "test.test@gmail.com", // Change to your verified sender
  subject: "Sending with SendGrid is Fun",
  text: "and easy to do anywhere, even with Node.js",
  html: "<strong>and easy to do anywhere, even with Node.js</strong>",
};

sgMail
  .send(msg)
  .then(() => {
    console.log("Email sent");
  })
  .catch((error) => {
    console.error(error);
  });

Error: Cannot find module 'sendgrid'
Require stack:
- /Users/tategraham/Downloads/send grid/sendGrid.js
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:900:15)
    at Function.Module._load (node:internal/modules/cjs/loader:745:27)
    at Module.require (node:internal/modules/cjs/loader:972:19)
    at require (node:internal/modules/cjs/helpers:88:18)
    at Object.<anonymous> (/Users/tategraham/Downloads/send grid/sendGrid.js:4:16)
    at Module._compile (node:internal/modules/cjs/loader:1083:30)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1112:10)
    at Module.load (node:internal/modules/cjs/loader:948:32)
    at Function.Module._load (node:internal/modules/cjs/loader:789:14)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:72:12) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [ '/Users/tategraham/Downloads/send grid/sendGrid.js' ]
}
tategraham@MacBook-Pro send grid % 

【问题讨论】:

  • 1.不要发布敏感内容(立即撤销该密钥)。 2.包是@sendgrid/client
  • 你安装了模块吗? sendgrid 也被弃用了,新的包可以在@sendgrid/mail找到
  • 我现在收到此错误:ategraham@MacBook-Pro send grid % node sendGrid.js API 密钥不以“SG.”开头。 ResponseError:在 node_modules/@sendgrid/client/src/classes/client.js:145:29 在 processTicksAndRejections (node:internal/process/task_queues:93:5) 处未授权

标签: javascript node.js firebase sendgrid


【解决方案1】:
const sgMail = require('@sendgrid/mail')
sgMail.setApiKey(process.env.SENDGRID_API_KEY)

这里是实际文档的链接: https://sendgrid.com/docs/for-developers/sending-email/quickstart-nodejs/#complete-code-block

关于使用环境变量的更新

首先创建 .env 文件,例如 sendgrid.env。然后你可以使用require('dotenv').config(sendgrid.env) 或者,也许,只是 require('dotenv').config(sendgrid)

然后你可以使用在那个env文件中定义的SENDGRID_API_KEY 至少根据我对你的问题的理解可以做到这一点。

【讨论】:

  • 谢谢 - 如何创建环境变量?
  • @TateGraham 看看dotenv。它用于从.env 文件中创建和读取环境变量
猜你喜欢
  • 2020-03-06
  • 2013-03-02
  • 1970-01-01
  • 1970-01-01
  • 2020-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-15
相关资源
最近更新 更多