Reputation: 29
I have created a node.js application and have successfully define a protected route with token. 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.
My app.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
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>
<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>
Upvotes: 0
Views: 1812
Reputation: 606
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.
To log in a user, you need to save the JWT in cookie or localStorage. That's not a very difficult task but remember to set the header of every requests on protected routes with the Bearer Token
You can follow this example: https://github.com/chaofz/jquery-jwt-auth/blob/master/index.html
localStorage.setItem('token', yourTokenresponseFromExpress);
Upvotes: 1