问题:MERN:Sendgrid 在尝试注册用户时返回 unathorized

我在这里有我的用户控制器,我测试在用户注册时发送电子邮件。

import expressAsyncHandler from 'express-async-handler'
import generateToken from '../utility/generateToken.js'
import sendGridMail from '@sendgrid/mail'
import User from '../models/userModel.js'

sendGridMail.setApiKey(process.env.SENDGRID_API_KEY);

// @description   Register a new user
// @route         POST /api/users
// @access        Public
const registerUser = expressAsyncHandler(async (req, res) => {
    const { name, email, phone, role, password } = req.body
    const userExists = await User.findOne({ email })
    
    if(userExists){
        res.status(400)
        throw new Error('User already exist!')
    }

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

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

    const emailData = {
        from: process.env.EMAIL_FROM,
        to: email,
        subject: `Iko account activation link`,
        html: `
           <h2>Please use the following link to activate your account</h2>
           <p>${process.env.CLIENT_URL}/auth/activate/${generateToken(name, email, password)}</p>
           <hr/>
           <p>This is email may contain sensitive information</p>
        `
    }

    const emailSent = await sendGridMail.send(emailData)

    if(emailSent){
        res.status(201).json({
              message: 'Email has been sent to ${email}. Follow the instruction to activate your account!'
        })
    }
 })

在邮递员中尝试在POST localhost/5000/api/users上进行注册时:

{
  "name": "Night Smith",
  "email": "smithnightgmail.com",
  "phone": "55555555",
  "role": "regular",
  "password": "12345"
 }

它返回给我:

{
    "message": "Unauthorized",
    "stack": "Error: Unauthorized\n    at C:\\Users\\MERN\\Desktop\\MERN\\Route\\node_modules\\@sendgrid\\client\\src\\classes\\client.js:145:29\n    
    at processTicksAndRejections (internal/process/task_queues.js:93:5)"
}

注意:我的 .env 文件中有这样的配置:

NODE_ENV = development
PORT = 5000
CLIENT_URL=http://localhost:3000
MONGO_URI = mongodb+srv://[i wont put it here]
SENDGRID_API_KEY=SG.f8oUiOv-T1Sg7JcJohi2Dg.k
JWT_SECRET = 123456
JWT_ACCOUNT_ACTIVATION=OKaUvaxUugsmCm3UmzeK0
EMAIL_TO=rodelgrace@gmail.com
EMAIL_FROM=noreply@mern.com.us
JWT_RESET_PASSWORD=5WrQQUc828AytLkBZvV70E7ePsAB9u

知道是什么导致这不发送电子邮件确认吗?我放置了它需要的所有必要细节。

解答

首先,您需要在 SendGrid 中拥有经过验证的Single Sender

它必须是网站电子邮件,例如。info@website.com.

我认为Gmail 不会工作。

其次,你需要把setApiKey放在寄存器函数里面:

// @description   Register a new user
// @route         POST /api/users
// @access        Public
const registerUser = expressAsyncHandler(async (req, res) => {
    const { name, email, phone, role, password } = req.body
    const userExists = await User.findOne({ email })
    
    if(userExists){
        res.status(400)
        throw new Error('User already exist!')
    }

    sendGridMail.setApiKey(process.env.SENDGRID_API_KEY)

    const emailData = {
        to: email,
        from: process.env.EMAIL_FROM,
        subject: `Iko account activation link`,
        html: `
           <h2>Please use the following link to activate your account</h2>
           <p>${process.env.CLIENT_URL}/auth/activate/${generateToken(name, email, password)}</p>
           <hr/>
           <p>This is email may contain sensitive information</p>
        `
    }

    const emailSent = await sgMail.send(emailData)

    if(emailSent){
        res.status(201).json({
              message: `Email has been sent to ${email}. Follow the instruction to activate your account!`
        })
    }


 })
Logo

MongoDB社区为您提供最前沿的新闻资讯和知识内容

更多推荐