vue mysql登录功能实现
实现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)
安装必要依赖:

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:

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();
}
});
测试流程
- 启动MySQL服务并创建数据库
- 运行Node.js服务器(node server.js)
- 启动Vue开发服务器(npm run serve)
- 访问前端页面测试登录功能






