当前位置:首页 > VUE

vue session实现登录

2026-02-19 21:12:35VUE

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');
      });
  }
}

后端注销路由

vue session实现登录

app.post('/api/logout', (req, res) => {
  req.session.destroy(err => {
    if (err) {
      return res.status(500).json({ success: false });
    }
    res.json({ success: true });
  });
});

生产环境注意事项

  1. 使用 HTTPS 确保安全传输
  2. 设置安全的 Cookie 属性
  3. 实现 CSRF 保护
  4. 使用安全的 Session 存储方式
  5. 实现密码哈希存储

以上实现展示了 Vue 前端与 Node.js 后端配合实现基于 Session 的认证系统的基本流程。实际应用中需要根据具体需求进行调整和完善。

标签: vuesession
分享给朋友:

相关文章

vue实现滚动中断

vue实现滚动中断

Vue 实现滚动中断的方法 在 Vue 中实现滚动中断通常涉及监听滚动事件,并在特定条件下阻止默认行为或停止滚动。以下是几种常见方法: 监听滚动事件并阻止默认行为 通过 @scroll 或 @whe…

vue实现人脸识别比对

vue实现人脸识别比对

Vue 实现人脸识别比对的方法 使用现成的人脸识别 API 通过调用第三方人脸识别 API(如 Face++、百度 AI、腾讯云等)实现比对功能。注册开发者账号获取 API Key 和 Secret,…

vue实现route

vue实现route

Vue 路由实现方法 Vue 中实现路由通常使用 vue-router 库,这是 Vue 官方推荐的路由管理器。以下是具体实现步骤: 安装 vue-router 通过 npm 或 yarn 安装…

vue网页实现

vue网页实现

Vue 网页实现指南 环境准备 安装 Node.js 和 npm/yarn,确保环境配置正确。使用 Vue CLI 或 Vite 创建项目框架,快速搭建开发环境。 npm install -g @v…

vue 实现协同

vue 实现协同

Vue 实现协同编辑的方案 协同编辑指多个用户同时编辑同一文档并实时同步更改。Vue 结合相关库和技术可轻松实现该功能。 使用 WebSocket 实现实时通信 WebSocket 提供全双工通信,…

vue实现左右菜单联动实现

vue实现左右菜单联动实现

Vue 实现左右菜单联动 使用事件总线通信 在 Vue 中可以通过事件总线实现左右菜单的通信。创建一个中央事件总线实例,让左右菜单通过事件监听和触发实现联动。 // eventBus.js impo…