Error: Cannot find module 'sendgrid' when using sendgrid

Error: Cannot find module 'sendgrid' when using sendgrid

我不断收到“错误:在尝试执行我的代码时无法在我的控制台中找到模块 '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 % 
const sgMail = require('@sendgrid/mail')
sgMail.setApiKey(process.env.SENDGRID_API_KEY)

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

关于使用环境变量的更新

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

然后你可以使用那个env文件中定义的SENDGRID_API_KEY 至少这个可以根据我对你的问题的理解来完成。