当前位置:首页 > VUE

vue 实现注册登录

2026-02-17 14:00:45VUE

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安全配置

vue 实现注册登录

app.use(cors({
  origin: 'https://yourdomain.com',
  methods: ['GET', 'POST'],
  allowedHeaders: ['Content-Type', 'Authorization']
}))

标签: vue
分享给朋友:

相关文章

vue实现多层评论回复

vue实现多层评论回复

Vue 实现多层评论回复 数据结构设计 多层评论通常采用嵌套结构,每个评论对象包含子评论数组。示例数据结构如下: comments: [ { id: 1, content: '父…

vue实现适老化样式

vue实现适老化样式

Vue 实现适老化样式的关键方法 全局字体与字号调整 通过 CSS 变量或主题配置统一放大基础字号,建议正文不小于 18px,标题更大。在 App.vue 中设置全局样式: :root { --…

vue架构实现

vue架构实现

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

vue实现博客

vue实现博客

Vue 实现博客的基本步骤 使用 Vue.js 实现一个博客系统可以分为前端和后端两部分。以下是基于 Vue 的前端实现方案,后端可以选择 Node.js、Django 或其他框架。 项目初始化 使…

vue 实现后退

vue 实现后退

实现后退功能的方法 在Vue中实现后退功能通常需要结合浏览器历史记录API或Vue Router的导航方法。以下是几种常见的实现方式: 使用Vue Router的go方法 this.$router…

vue实现筛选

vue实现筛选

实现筛选功能的基本思路 在Vue中实现筛选功能通常需要结合数据绑定、计算属性和方法。筛选的核心逻辑是根据用户输入的条件过滤原始数据列表,并动态更新显示结果。 数据准备 定义一个数组存储原始数据,另一…