简体   繁体   中英

NodeJS Sendgrid 401 unauthorized

After registering a user in my node express server, I would like to send a verification email. If the user is created I use this function to send the email:

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 }

It is called here:

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')
  }
})

The problem I am having is I get a ResponseError Unauthorized (code 401) when the request is made. The user does get created in the system. On my sendgrid account, I have verified the sender email with full access and I am storing my API Key in my.env file.

I have used 10 minute mail accounts to test this and real email accounts.

If the 401 status is coming from sendgrid then probably your env variable is not resolved. try this line after you import the dotenv package

dotenv.config()

If it didn't work, try to console.log the process.env.SENDGRID_API_KEY before u use it to make sure it's there.

import sgMail from '@sendgrid/mail' and set your api key sgMail.setApiKey('your api key is here')

I had the same issue. It was misleading because their SENDGRID_API_KEY matches up with the nomenclature of the smaller string. I figured the longer one was the secret. Use the longer string for the key. That one worked for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM