当前位置:首页 > VUE

node vue实现 登录注册

2026-01-23 11:30:12VUE

实现登录注册功能

在Node.js和Vue.js中实现登录注册功能,通常涉及前端Vue.js构建用户界面,后端Node.js处理业务逻辑和数据库交互。

后端Node.js实现

使用Express框架和MongoDB数据库创建后端API:

const express = require('express');
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const cors = require('cors');

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

mongoose.connect('mongodb://localhost:27017/auth_demo', {useNewUrlParser: true, useUnifiedTopology: true});

const UserSchema = new mongoose.Schema({
  username: {type: String, required: true, unique: true},
  email: {type: String, required: true, unique: true},
  password: {type: String, required: true}
});

const User = mongoose.model('User', UserSchema);

// 注册路由
app.post('/api/register', async (req, res) => {
  try {
    const {username, email, password} = req.body;
    const hashedPassword = await bcrypt.hash(password, 10);
    const user = new User({username, email, password: hashedPassword});
    await user.save();
    res.status(201).send('User created');
  } catch (error) {
    res.status(400).send(error.message);
  }
});

// 登录路由
app.post('/api/login', async (req, res) => {
  try {
    const {email, password} = req.body;
    const user = await User.findOne({email});
    if (!user) return res.status(400).send('User not found');

    const validPassword = await bcrypt.compare(password, user.password);
    if (!validPassword) return res.status(400).send('Invalid password');

    const token = jwt.sign({_id: user._id}, 'secretkey');
    res.header('auth-token', token).send(token);
  } catch (error) {
    res.status(400).send(error.message);
  }
});

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

前端Vue.js实现

使用Vue CLI创建项目并实现登录注册界面:

// main.js
import Vue from 'vue'
import App from './App.vue'
import axios from 'axios'
import router from './router'

Vue.config.productionTip = false
Vue.prototype.$http = axios.create({
  baseURL: 'http://localhost:3000/api'
})

new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

创建登录组件:

<!-- Login.vue -->
<template>
  <div>
    <h2>Login</h2>
    <form @submit.prevent="login">
      <input v-model="email" type="email" placeholder="Email" required>
      <input v-model="password" type="password" placeholder="Password" required>
      <button type="submit">Login</button>
    </form>
  </div>
</template>

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

创建注册组件:

<!-- Register.vue -->
<template>
  <div>
    <h2>Register</h2>
    <form @submit.prevent="register">
      <input v-model="username" type="text" placeholder="Username" 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>
  </div>
</template>

<script>
export default {
  data() {
    return {
      username: '',
      email: '',
      password: ''
    }
  },
  methods: {
    async register() {
      try {
        await this.$http.post('/register', {
          username: this.username,
          email: this.email,
          password: this.password
        });
        alert('Registration successful');
        this.$router.push('/login');
      } catch (error) {
        alert(error.response.data);
      }
    }
  }
}
</script>

路由配置

配置Vue Router管理页面导航:

// router.js
import Vue from 'vue'
import Router from 'vue-router'
import Login from './components/Login'
import Register from './components/Register'
import Dashboard from './components/Dashboard'

Vue.use(Router)

const router = new Router({
  routes: [
    { path: '/login', component: Login },
    { path: '/register', component: Register },
    { path: '/dashboard', component: Dashboard, meta: { requiresAuth: true } },
    { path: '*', redirect: '/login' }
  ]
})

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!localStorage.getItem('token')) {
      next('/login');
    } else {
      next();
    }
  } else {
    next();
  }
})

export default router

保护路由

创建需要认证的Dashboard组件:

<!-- Dashboard.vue -->
<template>
  <div>
    <h2>Welcome to Dashboard</h2>
    <button @click="logout">Logout</button>
  </div>
</template>

<script>
export default {
  methods: {
    logout() {
      localStorage.removeItem('token');
      this.$router.push('/login');
    }
  }
}
</script>

安全增强

在实际应用中,应考虑以下安全措施:

  • 使用HTTPS加密通信
  • 实现CSRF保护
  • 设置JWT过期时间
  • 密码强度验证
  • 输入数据验证和清理
  • 实现限流防止暴力破解

部署考虑

部署时需要注意:

  • 生产环境使用环境变量存储敏感信息
  • 数据库使用生产级配置
  • 前端构建后部署到Web服务器
  • 后端API部署到Node.js服务器或容器
  • 配置CORS策略限制跨域请求

以上实现提供了基础的登录注册功能,可以根据具体需求进行扩展和优化。

node vue实现 登录注册

标签: nodevue
分享给朋友:

相关文章

vue实现下拉框删除

vue实现下拉框删除

Vue 实现下拉框删除功能 在Vue中实现下拉框的删除功能通常涉及以下步骤: 数据绑定与渲染 在Vue组件中定义数据数组用于存储下拉框选项: data() { return { op…

vue实现muli

vue实现muli

Vue 实现多语言(i18n)支持 在 Vue 项目中实现多语言(i18n)功能,通常使用 vue-i18n 插件。以下是具体实现步骤: 安装 vue-i18n npm install vue…

vue实现登出

vue实现登出

实现Vue登出功能 登出功能通常涉及清除用户会话、令牌或本地存储的数据,并重定向到登录页面。以下是几种常见的实现方式: 清除用户令牌和状态 在Vuex的store中定义一个logout mutat…

vue实现长按

vue实现长按

Vue 实现长按功能的方法 在 Vue 中实现长按功能可以通过原生事件监听或自定义指令完成。以下是几种常见实现方式: 使用原生事件监听 通过 @mousedown 和 @mouseup 或 @tou…

vue实现标题

vue实现标题

Vue 实现标题的方法 在Vue中实现标题可以通过多种方式,以下是几种常见的方法: 方法一:使用模板语法 在Vue组件的模板中直接使用HTML的<h1>到<h6>标签来定义…

vue 实现modal

vue 实现modal

Vue 实现 Modal 的方法 使用 Vue 原生组件 通过 Vue 的组件系统可以轻松实现 Modal。创建一个可复用的 Modal 组件,通过 props 控制显示与隐藏。 <templ…