Node.js中无需用户名密码生成JWT令牌及跳转后验证方法咨询
Hey there! Since you're new to Node.js and JWT, let's walk through exactly how to build what you're asking for—generating a token without needing a username/password, handling the button click to generate and redirect, plus validating that token on the next page. I'll keep it simple and practical so you can follow along.
1. Set Up Your Node.js Backend (Token Generation & Validation)
First, we'll use the jsonwebtoken library to create and verify tokens, plus express for our API server.
Step 1: Install Dependencies
Open your terminal and run:
npm install jsonwebtoken express cors
Step 2: Write the Backend Code
Create a server.js file with this code:
const express = require('express'); const jwt = require('jsonwebtoken'); const cors = require('cors'); const app = express(); app.use(cors()); // Allow cross-origin requests from your frontend app.use(express.json()); // IMPORTANT: In production, store this secret in an environment variable, NOT hardcoded! const JWT_SECRET = 'your-super-secure-secret-key-change-this-in-production'; // API endpoint to generate a token (no username/password required) app.post('/generate-token', (req, res) => { // Create a dummy user object—you can customize this (e.g., random user ID, guest role) const anonymousUser = { userId: `guest-${Math.floor(Math.random() * 1000)}`, role: 'guest' }; // Generate JWT with an expiration time (1 hour here) const token = jwt.sign(anonymousUser, JWT_SECRET, { expiresIn: '1h' }); res.json({ token }); }); // API endpoint to validate a token app.post('/validate-token', (req, res) => { const { token } = req.body; if (!token) { return res.status(401).json({ valid: false, message: 'No token provided' }); } try { // Verify the token using our secret const decodedUser = jwt.verify(token, JWT_SECRET); res.json({ valid: true, user: decodedUser }); } catch (error) { // Token is invalid or expired res.status(401).json({ valid: false, message: 'Invalid or expired token' }); } }); // Start the server app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Let's create a simple index.html page with a button that triggers token generation and redirects:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Generate Token</title> </head> <body> <button id="generateTokenBtn">Generate Token & Go to Next Page</button> <script> const generateBtn = document.getElementById('generateTokenBtn'); generateBtn.addEventListener('click', async () => { try { // Call our backend to get the token const response = await fetch('http://localhost:3000/generate-token', { method: 'POST', headers: { 'Content-Type': 'application/json' } }); const data = await response.json(); // Store the token in localStorage so we can access it on the next page localStorage.setItem('accessToken', data.token); // Redirect to the next page (create next.html next!) window.location.href = 'next.html'; } catch (error) { console.error('Error generating token:', error); alert('Oops! Failed to generate token. Please try again.'); } }); </script> </body> </html>
3. Next Page: Validate the Token on Load
Create next.html to check the token when the page loads:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Next Page</title> </head> <body> <div id="validationMessage"></div> <script> window.addEventListener('load', async () => { const token = localStorage.getItem('accessToken'); const messageDiv = document.getElementById('validationMessage'); // If no token exists, send user back if (!token) { messageDiv.textContent = 'No token found! Please go back and generate one.'; messageDiv.style.color = 'red'; return; } try { // Call backend to validate the token const response = await fetch('http://localhost:3000/validate-token', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token }) }); const data = await response.json(); if (data.valid) { messageDiv.innerHTML = ` ✅ Token is valid! <br> Your User ID: ${data.user.userId} <br> Your Role: ${data.user.role} `; messageDiv.style.color = 'green'; } else { messageDiv.textContent = `❌ ${data.message}`; messageDiv.style.color = 'red'; // Optional: Redirect back to homepage // setTimeout(() => window.location.href = 'index.html', 3000); } } catch (error) { console.error('Error validating token:', error); messageDiv.textContent = 'Failed to validate token. Please try again.'; messageDiv.style.color = 'red'; } }); </script> </body> </html>
4. Critical Tips for Beginners
- Secure Your JWT Secret: Never hardcode your secret like I did above! Use the
dotenvpackage to store it in an environment variable. Install it withnpm install dotenv, create a.envfile withJWT_SECRET=your-secret-key, and addrequire('dotenv').config();at the top ofserver.js. - Token Storage Risks:
localStorageis easy but vulnerable to XSS attacks. For better security, use HttpOnly cookies (you'll need to adjust the backend to set cookies instead of returning the token in JSON). - Always Validate on Backend: Don't rely only on frontend checks—any protected routes should validate the token on the backend, since frontend code can be modified.
- Set Expiration Times: Always add an
expiresInvalue to your tokens so they don't stay valid forever.
内容的提问来源于stack exchange,提问作者asif308
相关产品推荐
相关产品推荐

