我正在嘗試執行我的登錄功能(我正在使用bcrypt和jsonwebtoken),問題是console.log(user._id)回傳給我 "new ObjectId(" 6148f043ebbaa0ab41ac8499 ")",而不是僅僅 "6148f043ebbaa0ab41ac8499",這對于創建令牌會更容易。
module。 exports.login = async (req, res) => {
const { email, password } = req.body;
//將req.body.password與DB中的散列密碼進行比較。
const user = await UserModel.findOne({ email: email })。
const match = await bcrypt.compare(password, user.password)。
if (match) {
try {
const user = await UserModel.findOne({ email: email })。
console.log(user._id) 。
//指定一個令牌。
const token = jwt.sign({ userId: user. _id }, process.env.LOGIN_TOKEN, {
expiresIn: "1h",
});
console.log(token)。
res.cookie("jwt"/span>, token, { httpOnly: true})。)
res.status(200).json({ user: user._id }) 。
} catch (err) {
res.status(500).json(err)。
}
} else {
res.status(500).json({message: "error!!" })。)
}
};
請問如何解決這個問題?
uj5u.com熱心網友回復:
這是一個正常的行為。因為你得到了一個ObjectId,你可以通過呼叫toHexString()方法將其轉換為一個字串。我還修改了代碼以檢查未定義的用戶,并洗掉了尋找用戶的額外呼叫,因為你已經在前一行做了。請看更新后的代碼:
module。 exports.login = async (req, res) => {
const { email, password } = req.body;
const user = await UserModel.findOne({ email: email })。
if (!user) {
return res.status(400).json({ message: "Unauthorised"})。)
}
//將req.body.password與DB中的散列密碼進行比較。
const match = await bcrypt.compare(password, user.password)。
if (match) {
try {
//將用戶ID(ObjectId)轉換成一個字串。
const userId = user._id.toHexString()。
//現在用戶ID是一個字串。
console.log(userId)。
//指定一個令牌。
const token = jwt.sign({ userId }, process.env.LOGIN_TOKEN, {
expiresIn: "1h",
});
console.log(token)。
res.cookie("jwt"/span>, token, { httpOnly: true})。)
res.status(200).json({ user })。
} catch (err) {
res.status(500).json(err)。
}
} else {
res.status(400).json({ message。"Unauthorised" })。)
}
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/331058.html
標籤:
