vue 实现注册登录
Vue 实现注册登录功能
前端部分(Vue 3 + Vite + Axios)
安装必要依赖
npm install axios vue-router pinia
创建路由文件(src/router/index.js)
import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/Login.vue'
import Register from '../views/Register.vue'
import Home from '../views/Home.vue'
const routes = [
{ path: '/login', component: Login },
{ path: '/register', component: Register },
{ path: '/', component: Home, meta: { requiresAuth: true } }
]
const router = createRouter({
history: createWebHistory(),
routes
})
router.beforeEach((to, from, next) => {
const isAuthenticated = localStorage.getItem('token')
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login')
} else {
next()
}
})
export default router
创建登录组件(src/views/Login.vue)
<template>
<form @submit.prevent="handleLogin">
<input v-model="email" type="email" placeholder="Email" required>
<input v-model="password" type="password" placeholder="Password" required>
<button type="submit">Login</button>
</form>
</template>
<script setup>
import { ref } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'
const email = ref('')
const password = ref('')
const router = useRouter()
const handleLogin = async () => {
try {
const response = await axios.post('http://localhost:3000/api/login', {
email: email.value,
password: password.value
})
localStorage.setItem('token', response.data.token)
router.push('/')
} catch (error) {
alert('Login failed')
}
}
</script>
创建注册组件(src/views/Register.vue)
<template>
<form @submit.prevent="handleRegister">
<input v-model="name" type="text" placeholder="Name" required>
<input v-model="email" type="email" placeholder="Email" required>
<input v-model="password" type="password" placeholder="Password" required>
<button type="submit">Register</button>
</form>
</template>
<script setup>
import { ref } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'
const name = ref('')
const email = ref('')
const password = ref('')
const router = useRouter()
const handleRegister = async () => {
try {
await axios.post('http://localhost:3000/api/register', {
name: name.value,
email: email.value,
password: password.value
})
router.push('/login')
} catch (error) {
alert('Registration failed')
}
}
</script>
后端部分(Node.js + Express + MongoDB)
安装后端依赖
npm install express mongoose bcryptjs jsonwebtoken cors body-parser
创建服务器文件(server.js)
const express = require('express')
const mongoose = require('mongoose')
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const cors = require('cors')
const bodyParser = require('body-parser')
const app = express()
app.use(cors())
app.use(bodyParser.json())
mongoose.connect('mongodb://localhost:27017/auth_demo')
const UserSchema = new mongoose.Schema({
name: String,
email: { type: String, unique: true },
password: String
})
const User = mongoose.model('User', UserSchema)
app.post('/api/register', async (req, res) => {
try {
const hashedPassword = await bcrypt.hash(req.body.password, 10)
const user = new User({
name: req.body.name,
email: req.body.email,
password: hashedPassword
})
await user.save()
res.status(201).send({ message: 'User created' })
} catch (error) {
res.status(500).send({ error: 'Registration failed' })
}
})
app.post('/api/login', async (req, res) => {
const user = await User.findOne({ email: req.body.email })
if (!user) return res.status(400).send({ error: 'User not found' })
const validPassword = await bcrypt.compare(req.body.password, user.password)
if (!validPassword) return res.status(400).send({ error: 'Invalid password' })
const token = jwt.sign({ _id: user._id }, 'SECRET_KEY')
res.send({ token })
})
app.listen(3000, () => console.log('Server running on port 3000'))
安全增强措施
使用环境变量存储敏感信息
创建.env文件
JWT_SECRET=your_secure_secret_key
DB_CONNECTION=mongodb://localhost:27017/auth_demo
使用HTTPS保护数据传输
const https = require('https')
const fs = require('fs')
const options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
}
https.createServer(options, app).listen(3000)
实现密码强度验证
function validatePassword(password) {
const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$/
return regex.test(password)
}
部署注意事项
配置生产环境变量 设置Nginx反向代理
server {
listen 80;
server_name yourdomain.com;
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
启用CORS安全配置
app.use(cors({
origin: 'https://yourdomain.com',
methods: ['GET', 'POST'],
allowedHeaders: ['Content-Type', 'Authorization']
}))






