vue session实现登录
Vue 中实现 Session 登录
在 Vue 中实现基于 Session 的登录通常需要前后端配合,前端负责发送登录请求并处理响应,后端负责验证用户信息并创建 Session。
前端实现步骤
安装 axios 用于发送 HTTP 请求
npm install axios
创建登录组件
<template>
<div>
<input v-model="username" placeholder="Username">
<input v-model="password" type="password" placeholder="Password">
<button @click="login">Login</button>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
username: '',
password: ''
}
},
methods: {
login() {
axios.post('/api/login', {
username: this.username,
password: this.password
})
.then(response => {
if (response.data.success) {
// 登录成功后的处理
this.$router.push('/dashboard');
}
})
.catch(error => {
console.error('Login failed:', error);
});
}
}
}
</script>
配置 axios 默认设置 在 main.js 或单独配置文件中添加:
import axios from 'axios';
axios.defaults.withCredentials = true; // 允许跨域携带 cookie
后端实现示例 (Node.js/Express)
安装必要依赖
npm install express express-session body-parser cors
创建服务器代码
const express = require('express');
const session = require('express-session');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
// 配置中间件
app.use(cors({
origin: 'http://localhost:8080', // Vue 开发服务器地址
credentials: true
}));
app.use(bodyParser.json());
app.use(session({
secret: 'your-secret-key',
resave: false,
saveUninitialized: false,
cookie: { secure: false } // 开发环境设为 false,生产环境应设为 true
}));
// 登录路由
app.post('/api/login', (req, res) => {
const { username, password } = req.body;
// 实际应用中应该查询数据库验证用户
if (username === 'admin' && password === 'password') {
req.session.user = { username };
res.json({ success: true });
} else {
res.status(401).json({ success: false });
}
});
// 受保护的路由
app.get('/api/protected', (req, res) => {
if (req.session.user) {
res.json({ message: 'Welcome ' + req.session.user.username });
} else {
res.status(401).json({ message: 'Unauthorized' });
}
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
检查登录状态
在 Vue 应用中,可以创建一个全局导航守卫来检查用户是否已登录:
// 在 router/index.js 中
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
axios.get('/api/protected')
.then(() => next())
.catch(() => next('/login'));
} else {
next();
}
});
注销功能实现
前端注销方法
methods: {
logout() {
axios.post('/api/logout')
.then(() => {
this.$router.push('/login');
});
}
}
后端注销路由
app.post('/api/logout', (req, res) => {
req.session.destroy(err => {
if (err) {
return res.status(500).json({ success: false });
}
res.json({ success: true });
});
});
生产环境注意事项
- 使用 HTTPS 确保安全传输
- 设置安全的 Cookie 属性
- 实现 CSRF 保护
- 使用安全的 Session 存储方式
- 实现密码哈希存储
以上实现展示了 Vue 前端与 Node.js 后端配合实现基于 Session 的认证系统的基本流程。实际应用中需要根据具体需求进行调整和完善。







