当前位置:首页 > VUE

vue mysql登录功能实现

2026-02-22 04:30:04VUE

实现Vue与MySQL登录功能

前端部分(Vue)

安装axios用于发送HTTP请求:

npm install axios

创建登录表单组件(Login.vue):

<template>
  <div>
    <input v-model="username" placeholder="用户名">
    <input v-model="password" type="password" placeholder="密码">
    <button @click="login">登录</button>
    <p v-if="errorMessage">{{ errorMessage }}</p>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      username: '',
      password: '',
      errorMessage: ''
    }
  },
  methods: {
    async login() {
      try {
        const response = await axios.post('http://localhost:3000/login', {
          username: this.username,
          password: this.password
        });
        localStorage.setItem('token', response.data.token);
        this.$router.push('/dashboard');
      } catch (error) {
        this.errorMessage = error.response.data.message;
      }
    }
  }
}
</script>

后端部分(Node.js + MySQL)

安装必要依赖:

vue mysql登录功能实现

npm install express mysql2 body-parser cors jsonwebtoken bcryptjs

创建服务器文件(server.js):

const express = require('express');
const mysql = require('mysql2');
const bodyParser = require('body-parser');
const cors = require('cors');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');

const app = express();
app.use(bodyParser.json());
app.use(cors());

// 创建MySQL连接
const db = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'yourpassword',
  database: 'auth_db'
});

// 登录路由
app.post('/login', async (req, res) => {
  const { username, password } = req.body;

  db.query(
    'SELECT * FROM users WHERE username = ?',
    [username],
    async (err, results) => {
      if (err) throw err;

      if (results.length === 0) {
        return res.status(401).json({ message: '用户不存在' });
      }

      const user = results[0];
      const isMatch = await bcrypt.compare(password, user.password);

      if (!isMatch) {
        return res.status(401).json({ message: '密码错误' });
      }

      const token = jwt.sign(
        { id: user.id, username: user.username },
        'yourSecretKey',
        { expiresIn: '1h' }
      );

      res.json({ token });
    }
  );
});

app.listen(3000, () => {
  console.log('服务器运行在端口3000');
});

数据库准备

创建用户表SQL:

vue mysql登录功能实现

CREATE DATABASE auth_db;

USE auth_db;

CREATE TABLE users (
  id INT AUTO_INCREMENT PRIMARY KEY,
  username VARCHAR(50) NOT NULL UNIQUE,
  password VARCHAR(255) NOT NULL
);

-- 插入测试用户(密码使用bcrypt加密后的字符串)
INSERT INTO users (username, password) VALUES 
('testuser', '$2a$10$xJwL5v5z3U9x5Z5q5v5Z5e');

安全注意事项

使用bcrypt加密存储密码:

const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(password, salt);

实现JWT验证中间件:

function authenticateToken(req, res, next) {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];

  if (!token) return res.sendStatus(401);

  jwt.verify(token, 'yourSecretKey', (err, user) => {
    if (err) return res.sendStatus(403);
    req.user = user;
    next();
  });
}

前端路由保护

在Vue router中添加导航守卫:

router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('token');

  if (to.meta.requiresAuth && !isAuthenticated) {
    next('/login');
  } else {
    next();
  }
});

测试流程

  1. 启动MySQL服务并创建数据库
  2. 运行Node.js服务器(node server.js)
  3. 启动Vue开发服务器(npm run serve)
  4. 访问前端页面测试登录功能

标签: 功能vue
分享给朋友:

相关文章

vue实现视频会议

vue实现视频会议

使用 Vue 实现视频会议 技术选型 Vue.js 作为前端框架,结合 WebRTC 技术实现实时音视频通信。常用的库包括: peerjs:简化 WebRTC 的点对点连接。 socket.io:用…

vue架构实现

vue架构实现

Vue 架构实现核心方案 Vue.js 的架构实现通常围绕模块化、组件化和状态管理展开。以下为常见实现方案: 基于单文件组件(SFC)的模块化 通过 .vue 文件组织模板、脚本和样式: <…

vue 实现fadeout

vue 实现fadeout

Vue 实现淡出效果 在 Vue 中实现淡出(fade-out)效果可以通过 CSS 过渡或动画结合 Vue 的动态渲染功能完成。以下是几种常见方法: 使用 Vue 过渡(Transition)组件…

vue实现swiper

vue实现swiper

Vue 中实现 Swiper 的方法 安装 Swiper 依赖 在 Vue 项目中安装 Swiper 和相关依赖: npm install swiper vue-awesome-swiper 全局引…

vue遮罩实现

vue遮罩实现

实现 Vue 遮罩的常见方法 使用 CSS 定位和透明度 创建一个全屏遮罩层,通过 CSS 固定定位覆盖整个视口,并设置半透明背景色。 <template> <div cl…

vue实现插件

vue实现插件

Vue 插件实现方法 Vue 插件通常用于为 Vue 应用添加全局功能或共享功能。以下是实现 Vue 插件的核心步骤: 插件基本结构 Vue 插件需要暴露一个 install 方法,该方法接收 Vu…