当前位置:首页 > VUE

vue实现登录注册mysql

2026-01-23 03:12:33VUE

Vue 前端实现登录注册

创建 Vue 项目并安装必要依赖:

vue create vue-auth-demo
cd vue-auth-demo
npm install axios vue-router vuex

配置路由(router/index.js):

import Vue from 'vue'
import Router from 'vue-router'
import Login from '../views/Login.vue'
import Register from '../views/Register.vue'

Vue.use(Router)

export default new Router({
  routes: [
    { path: '/login', component: Login },
    { path: '/register', component: Register }
  ]
})

登录组件示例(Login.vue):

<template>
  <div>
    <input v-model="email" placeholder="Email">
    <input v-model="password" type="password" placeholder="Password">
    <button @click="login">Login</button>
  </div>
</template>

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

Node.js 后端实现

创建 Express 服务端:

mkdir server
cd server
npm init -y
npm install express mysql2 body-parser cors jsonwebtoken bcryptjs

数据库连接配置(db.js):

const mysql = require('mysql2')

const pool = mysql.createPool({
  host: 'localhost',
  user: 'root',
  password: 'yourpassword',
  database: 'auth_demo',
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
})

module.exports = pool.promise()

用户模型(models/user.js):

const db = require('../db')
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')

class User {
  static async create({ email, password }) {
    const hashedPassword = await bcrypt.hash(password, 10)
    const [result] = await db.execute(
      'INSERT INTO users (email, password) VALUES (?, ?)',
      [email, hashedPassword]
    )
    return result.insertId
  }

  static async findByEmail(email) {
    const [rows] = await db.execute(
      'SELECT * FROM users WHERE email = ?',
      [email]
    )
    return rows[0]
  }
}

module.exports = User

MySQL 数据库设置

创建数据库和用户表:

CREATE DATABASE auth_demo;

USE auth_demo;

CREATE TABLE users (
  id INT AUTO_INCREMENT PRIMARY KEY,
  email VARCHAR(255) NOT NULL UNIQUE,
  password VARCHAR(255) NOT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

前后端联调

启动前端开发服务器:

npm run serve

启动后端服务器(server/index.js):

const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const User = require('./models/user')

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

app.post('/register', async (req, res) => {
  try {
    await User.create(req.body)
    res.status(201).json({ message: 'User created' })
  } catch (error) {
    res.status(400).json({ error: error.message })
  }
})

app.post('/login', async (req, res) => {
  const user = await User.findByEmail(req.body.email)
  if (!user) return res.status(404).json({ error: 'User not found' })

  const isValid = await bcrypt.compare(req.body.password, user.password)
  if (!isValid) return res.status(401).json({ error: 'Invalid password' })

  const token = jwt.sign({ id: user.id }, 'your-secret-key', { expiresIn: '1h' })
  res.json({ token })
})

app.listen(3000, () => console.log('Server running on port 3000'))

安全增强措施

实现密码加密存储:

const saltRounds = 10
const hashedPassword = await bcrypt.hash(password, saltRounds)

添加 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, 'your-secret-key', (err, user) => {
    if (err) return res.sendStatus(403)
    req.user = user
    next()
  })
}

部署注意事项

配置生产环境变量:

# .env
DB_HOST=localhost
DB_USER=root
DB_PASSWORD=securepassword
DB_NAME=auth_demo
JWT_SECRET=complexsecretkey

前端打包部署:

npm run build

后端进程管理(使用 PM2):

vue实现登录注册mysql

npm install pm2 -g
pm2 start index.js

标签: vuemysql
分享给朋友:

相关文章

vue实现旋转

vue实现旋转

Vue 实现旋转效果的方法 在 Vue 中实现旋转效果可以通过多种方式完成,以下是几种常见的方法: 使用 CSS 动画 通过 Vue 的 :class 或 :style 绑定 CSS 动画实现旋转效…

vue 实现pdf

vue 实现pdf

在Vue中实现PDF功能 在Vue项目中实现PDF功能通常涉及PDF生成、预览或下载。以下是几种常见实现方式: 使用vue-pdf库预览PDF 安装依赖: npm install vue-pdf…

vue实现盖章

vue实现盖章

Vue 实现盖章功能 在Vue中实现盖章功能通常涉及前端UI交互,通过Canvas或SVG绘制印章,并允许用户拖拽或点击放置印章。以下是具体实现方法: 使用Canvas绘制印章 通过HTML5的Ca…

vue vnode实现

vue vnode实现

Vue VNode 实现原理 VNode(Virtual Node)是 Vue 的核心概念之一,用于描述真实 DOM 的轻量级虚拟表示。VNode 的实现涉及以下关键点: VNode 的基本结构 V…

vue原理实现

vue原理实现

Vue 原理实现的核心机制 Vue.js 的核心原理基于响应式系统、虚拟 DOM 和模板编译。以下是其核心实现机制的分解: 响应式系统 Vue 使用 Object.defineProperty(Vu…

vue实现ios

vue实现ios

Vue 实现 iOS 风格应用 使用 Vue 实现 iOS 风格的应用,可以通过结合 UI 框架和自定义样式来达成目标。以下是具体方法和步骤: 选择 iOS 风格的 UI 框架 Vue 生态中有多…