如何從 JsonwebToken 存盤和獲取 req.user 我正在使用節點開發預訂應用程式現在唯一要做的就是獲取預訂產品的用戶資訊并將其顯示在管理門戶中
.then((user) => {
const maxAge = 3 * 60 * 60;
const token = jwt.sign(
{ id: user._id, username, role: user.role },
jwtSecret,
{
expiresIn: maxAge, // 3hrs
}
);
res.cookie("jwt", token, {
httpOnly: true,
maxAge: maxAge * 1000,
});
現在我想從我擁有的任何路由器訪問用戶 ID
uj5u.com熱心網友回復:
將令牌傳遞到您的后端并對其進行反序列化以獲取您需要的資料。
app.use("/your_route", async function (req, res, next)
{
console.log( req.headers.cookie);
var token = ""
//HERE GET YOUR JWT and put it in variable token
//jwtSecret is your secret jwt
var tokenData = jwt.verify(token, jwtSecret)
console.log(tokenData);
}
uj5u.com熱心網友回復:
安裝 npm jwt-decode
const jwt_decode=require( "jwt-decode");
//make a middleware and call it where you need the jws id
exports.userId = (req,res,next)=> {
const token=req.cookies.jwt;
const {id,role} =
jwt_decode
(token);
req.userId = id; // Add to req object
next();
}
這是我想要用戶標識的檔案
router.get("/",userId, async (req, res) => {
try {
const id = req.userId;
console.log(id);
} catch (e) {
console.log(e);
}
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/456612.html
標籤:javascript 节点.js json 表示 猫鼬
