[英]How do you integrate HTML page with JWT Node JS Auth?
I have created a node.js application and have successfully define a protected route with token.我创建了一个 node.js 应用程序并成功定义了一个带有令牌的受保护路由。 I can run it via POSTMAN. I am trying to understand how then do I integrate this into a HTML page and login and call out the protected route to display on a HTML page instead of using POSTMAN. I am creating a html website and want a user login and then they can access certain link in the page.我可以通过 POSTMAN 运行它。我试图了解如何将其集成到 HTML 页面并登录并调出受保护的路由以显示在 HTML 页面上而不是使用 POSTMAN。我正在创建一个 html 网站并想要一个用户登录,然后他们可以访问页面中的某些链接。
My app.js我的应用程序.js
app.post('/api/posts', verifyToken, (req, res) => {
jwt.verify(req.token, secretKey, (err, authData) => {
if(err) {
res.sendStatus(403);
} else {
res.json({
message: 'Post created...',
authData : authData,
});
}
});
}); });
app.post('/api/login', (req, res) => { // Mock user app.post('/api/login', (req, res) => { // 模拟用户
var email=req.body.email;
var password=req.body.password;
const userdata = {
email: email,
password: password
}
console.log(userdata);
jwt.sign({userdata}, secretKey, (err, token) => {
res.json({
token
});
});
}); });
my HTML我的 HTML
<html>
<head>
</head>
<body>
<div>
<h1>Portal API Test site</h1>
<form action="/api/posts", method="POST">
<h2>Getting from Header</h2>
<input type="submit" value="Submit", >
</form>
</div>
</body>
First of all, i will suggest you to use at least a small framework to make the work easier for you such as react, svelte... Otherwise you can jQuery to do that.首先,我建议您至少使用一个小型框架来简化您的工作,例如 react、svelte ... 否则您可以使用 jQuery 来做到这一点。
To log in a user, you need to save the JWT in cookie or localStorage.登录用户需要将JWT保存在cookie或localStorage中。 That's not a very difficult task but remember to set the header of every requests on protected routes with the Bearer Token这不是一项非常困难的任务,但请记住使用 Bearer Token 在受保护路由上设置每个请求的 header
You can follow this example: https://github.com/chaofz/jquery-jwt-auth/blob/master/index.html你可以按照这个例子: https://github.com/chaofz/jquery-jwt-auth/blob/master/index.html
localStorage.setItem('token', yourTokenresponseFromExpress);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.