【问题标题】:NodeJS Sendgrid 401 unauthorizedNodeJS Sendgrid 401 未经授权
【发布时间】:2021-04-08 11:36:24
【问题描述】:

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

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 分钟邮件帐户来测试这个和真实的电子邮件帐户。

【问题讨论】:

    标签: javascript node.js sendgrid


    【解决方案1】:
    推荐的答案 Twilio

    如果 401 状态来自 sendgrid 则可能您的环境变量未解析。 导入 dotenv 包后尝试此行

    dotenv.config()
    

    如果它不起作用,请在使用之前尝试控制台记录process.env.SENDGRID_API_KEY 以确保它在那里。

    【讨论】:

      【解决方案2】:

      从 '@sendgrid/mail' 导入 sgMail 并设置你的 api 密钥 sgMail.setApiKey('你的 api 密钥在这里')

      【讨论】:

      • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
      • 请使用代码 cmets 即兴回答
      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-03-06
        • 2018-05-19
        • 2020-06-11
        • 2017-02-22
        • 2018-10-08
        • 2018-01-05
        • 1970-01-01
        相关资源
        最近更新 更多