NodeJS Sendgrid 401 未经授权

NodeJS Sendgrid 401 unauthorized

在我的节点快递服务器上注册用户后,我想发送一封验证邮件。如果创建了用户,我使用此功能发送电子邮件:

import dotenv from 'dotenv'
import sgMail from '@sendgrid/mail'

sgMail.setApiKey(process.env.SENDGRID_API_KEY)

const sendEmail = (to, token) => {
    const msg = {
        to,
        from: process.env.SENDGRID_SENDER,
        subject: 'Email Verification',
        text: `Please click the following link: http://localhost:5000/${token}`
    }
    
    sgMail
     .send(msg)
     .then((response) => {
        console.log(response[0].statusCode)
        console.log(response[0].headers)
    })
     .catch((error) => {
        console.error(error)
    })
}

export { sendEmail }

这里调用:

const registerUser = asyncHandler(async (req, res) => {
  const { name, email, password } = req.body

  const userExists = await User.findOne({ email })

  if (userExists) {
    res.status(400)
    throw new Error('User already exists')
  }

  const user = await User.create({
    name,
    email,
    password
  })

  if (user) {
    sendEmail(user.email, user.token) //HERE
    res.status(201).json({
      _id: user._id,
      name: user.name,
      email: user.email,
      isAdmin: user.isAdmin,
      isVerified: user.isVerified,
      token: generateToken(user._id),
    })
  } else {
    res.status(400)
    throw new Error('Invalid user data')
  }
})

我遇到的问题是在发出请求时收到 ResponseError Unauthorized(代码 401)。用户确实在系统中创建。在我的 sendgrid 帐户上,我已经验证了具有完全访问权限的发件人电子邮件,并且我将我的 API 密钥存储在我的 .env 文件中。

我已经使用 10 分钟的邮件帐户来测试这个和真实的电子邮件帐户。

如果 401 状态来自 sendgrid 那么您的环境变量可能没有解析。 导入 dotenv

后试试这一行
dotenv.config()

如果它不起作用,请在使用它之前尝试 console.log process.env.SENDGRID_API_KEY 以确保它在那里。

从“@sendgrid/mail”导入 sgMail 并设置您的 api 密钥 sgMail.setApiKey('your api key is here')

我遇到了同样的问题。这是误导,因为它们的 SENDGRID_API_KEY 与较小字符串的命名法相匹配。我认为更长的是秘密。使用较长的字符串作为密钥。那个对我有用。