后端用node前端vue怎么实现jwt鉴权
npm install jsonwebtoken --save
然后,下面是一个简单的例子,说明如何在 Node.js 后端和 Vue.js 前端中使用 JWT 进行用户身份验证。
- 后端:
const express = require('express'); const jwt = require('jsonwebtoken'); const app = express(); // 设置 JWT 加密密钥,保存在环境变量或文件中更安全 const JWT_SECRET = 'my_secret_key'; // 登录请求 app.post('/api/login', (req, res) => { const username = req.body.username; const password = req.body.password; // 在数据库中验证用户名和密码是否正确,验证通过之后生成 token 并返回给前端 if (username === 'admin' && password === '123456') { const user = { id: 1, username: 'admin' }; const token = jwt.sign(user, JWT_SECRET); res.json({ token: token }); } else { res.status(401).json({ error: 'Unauthorized access' }); } }); // 需要进行身份验证的 API 请求 app.get('/api/data', verifyToken, (req, res) => { // 通过验证,处理 API 逻辑 res.json({ message: 'Hello, JWT' }); }); // 验证 JWT token 的中间件 function verifyToken(req, res, next) { // 获取请求头中的 token const token = req.headers.authorization ? req.headers.authorization.split(' ')[1] : null; if (token === null) { res.status(401).json({ error: 'Unauthorized access' }); return; } // 验证 token 是否有效 jwt.verify(token, JWT_SECRET, (err, decoded) => { if (err) { res.status(401).json({ error: 'Unauthorized access' }); return; } // 在请求中继续使用该 token req.token = token; req.user = decoded; next(); }); } // 启动服务器 app.listen(3000, () => { console.log('Server is listening on port 3000.'); });
前端
-
<template> <div> <h1>{{ message }}</h1> </div> </template> <script> import axios from 'axios'; export default { data() { return { message: '' }; }, created() { // 在发送 API 请求前,将 token 添加到请求头,携带用户身份验证信息 const token = localStorage.getItem('token'); if (token) { axios.defaults.headers.common['Authorization'] = `Bearer ${token}`; } axios .get('/api/data') .then(response => { this.message = response.data.message; }) .catch(error => { console.log(error); if (error.response.status === 401) { this.$router.push('/login'); // 跳转到登录页面 } }); } }; </script>