英文:
How to store the login data in session storage and retrieve while commenting using node js
问题
我已经构建了一个登录 API 并添加了一个评论 API。登录详细信息和评论详细信息存储在Postgres DB中的不同表中。在评论时如何检索已登录的用户名?是否需要使用会话存储?如果需要,如何使用?
登录
const admin = await loginData.findOne({ where: { email } });
if (admin && (await bcrypt.compare(password, admin.password))) {
const token = jwt.sign(
{ admin_id: admin._id, email },
process.env.TOKEN_KEY,
{
expiresIn: "365d",
}
);
admin.token = token;
}
评论
try {
const { comment } = req.body;
const stageComment = await initCommentModel();
const id = req.params.id;
// 创建评论
await stageComment.create({
comment: comment,
stage_id: id,
});
return res.send("SUCCESS");
} catch (err) {
return res.send(err.stack);
}
英文:
I have built a login API and added a comment API. login details and comment details are stored in a different table in Postgres DB. while commenting on how to retrieve the logged-in username. is there a need to use the session storage? if yes how to use that?
login
const admin = await loginData.findOne({ where: { email } });
if (admin && (await bcrypt.compare(password, admin.password))) {
const token = jwt.sign(
{ admin_id: admin._id, email },
process.env.TOKEN_KEY,
{
expiresIn: "365d",
}
);
admin.token = token;
}
comment
try {
const { comment } = req.body;
const stageComment = await initCommentModel();
const id = req.params.id;
// create comment
await stageComment.create({
comment: comment,
stage_id: id,
});
return res.send("SUCCESS");
} catch (err) {
return res.send(err.stack);
}
答案1
得分: 1
好的,以下是翻译好的部分:
"well, as i see you use jwt token for login so you comment api should verify token token before to do somehting else."
"你好,从我看到的情况来看,你在登录时使用了JWT令牌,所以你的评论API在执行其他操作之前应该验证令牌。"
"You have to write middleware in express JS to authetheticate and verify if token is present in header or token is valid or not then you can add the login info into req like req.email = currentloginuser@gmail.com
."
"你需要在Express JS中编写中间件来进行身份验证并验证标头中是否存在令牌,以及令牌是否有效,然后你可以将登录信息添加到req
中,如 req.email = currentloginuser@gmail.com
。"
"you can store that token into session storage or localstorage on front end side."
"你可以将该令牌存储在前端的会话存储或本地存储中。"
英文:
well, as i see you use jwt token for login so you comment api should verify token token before to do somehting else.
You have to write middleware in express JS to authetheticate and verify if token is present in header or token is valid or not then you can add the login info into req like req.email = currentloginuser@gmail.com
.
you can store that token into session storage or localstorage on front end side.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论