[英]NodeJS Sendgrid 401 unauthorized
在我的節點快遞服務器中注冊用戶后,我想發送驗證 email。 如果創建了用戶,我使用此 function 發送 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 }
它在這里被調用:
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 帳戶上,我已經驗證了具有完全訪問權限的發件人 email 並且我將我的 API 密鑰存儲在 my.env 文件中。
我使用了 10 分鍾的郵件帳戶來測試這個和真實的 email 帳戶。
如果 401 狀態來自sendgrid ,那么您的 env 變量可能未解析。 導入dotenv
package 后嘗試此行
dotenv.config()
如果它不起作用,請在使用它之前嘗試控制台記錄process.env.SENDGRID_API_KEY
以確保它在那里。
從 '@sendgrid/mail' 導入 sgMail 並設置您的 api 密鑰 sgMail.setApiKey('您的 api 密鑰在這里')
我遇到過同樣的問題。 這是誤導性的,因為它們的 SENDGRID_API_KEY 與較小字符串的命名法相匹配。 我認為更長的時間是秘密。 使用較長的字符串作為密鑰。 那個對我有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.