微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

错误:使用sendgrid时找不到模块'sendgrid'

如何解决错误:使用sendgrid时找不到模块'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)

以下是指向实际文档的链接: 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)

然后,您可以使用该环境文件中定义的SENDGRID_API_KEY,至少可以根据我对您问题的理解来完成。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。