当前位置:首页 > VUE

node vue实现 登录注册

2026-02-24 02:06:39VUE

实现登录注册功能

使用Node.js和Vue.js实现登录注册功能需要分为后端(Node.js)和前端(Vue.js)两部分。以下是一个完整的实现方案。

后端部分(Node.js)

使用Express框架搭建后端服务,处理用户注册和登录请求。

安装依赖

npm install express body-parser bcryptjs jsonwebtoken mongoose cors

创建后端代码

const express = require('express');
const bodyParser = require('body-parser');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const mongoose = require('mongoose');
const cors = require('cors');

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

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

const User = mongoose.model('User', {
  username: String,
  password: String
});

app.post('/register', async (req, res) => {
  const { username, password } = req.body;
  const hashedPassword = await bcrypt.hash(password, 10);
  const user = new User({ username, password: hashedPassword });
  await user.save();
  res.status(201).send({ message: 'User registered successfully' });
});

app.post('/login', async (req, res) => {
  const { username, password } = req.body;
  const user = await User.findOne({ username });
  if (!user) return res.status(404).send({ message: 'User not found' });
  const isPasswordValid = await bcrypt.compare(password, user.password);
  if (!isPasswordValid) return res.status(401).send({ message: 'Invalid credentials' });
  const token = jwt.sign({ username: user.username }, 'secret_key', { expiresIn: '1h' });
  res.send({ token });
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});

前端部分(Vue.js)

使用Vue.js创建前端页面,实现用户注册和登录功能。

node vue实现 登录注册

安装依赖

npm install axios vue-router

创建前端代码

<template>
  <div>
    <h2>Register</h2>
    <input v-model="registerUsername" placeholder="Username">
    <input v-model="registerPassword" type="password" placeholder="Password">
    <button @click="register">Register</button>

    <h2>Login</h2>
    <input v-model="loginUsername" placeholder="Username">
    <input v-model="loginPassword" type="password" placeholder="Password">
    <button @click="login">Login</button>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      registerUsername: '',
      registerPassword: '',
      loginUsername: '',
      loginPassword: ''
    };
  },
  methods: {
    async register() {
      try {
        await axios.post('http://localhost:3000/register', {
          username: this.registerUsername,
          password: this.registerPassword
        });
        alert('Registration successful');
      } catch (error) {
        alert('Registration failed');
      }
    },
    async login() {
      try {
        const response = await axios.post('http://localhost:3000/login', {
          username: this.loginUsername,
          password: this.loginPassword
        });
        localStorage.setItem('token', response.data.token);
        alert('Login successful');
      } catch (error) {
        alert('Login failed');
      }
    }
  }
};
</script>

整合前后端

  1. 启动后端服务:确保MongoDB服务已启动,运行node server.js启动后端。
  2. 启动前端服务:运行npm run serve启动Vue.js前端。
  3. 测试功能:访问前端页面,测试注册和登录功能。

注意事项

  • 后端使用JWT进行身份验证,前端将token存储在localStorage中。
  • 密码使用bcryptjs进行加密存储,确保安全性。
  • 使用cors中间件处理跨域请求,确保前后端可以正常通信。

标签: nodevue
分享给朋友:

相关文章

vue实现拖放

vue实现拖放

Vue 实现拖放功能 Vue 中实现拖放功能通常可以通过 HTML5 的原生拖放 API 或第三方库(如 vuedraggable)来实现。以下是两种方法的详细说明。 使用 HTML5 原生拖放 A…

vue 实现级联

vue 实现级联

Vue 实现级联选择器 级联选择器(Cascader)常用于省市区选择、分类选择等场景。Vue 中可以通过 Element UI、Ant Design Vue 等 UI 库实现,也可以手动封装。 使…

vue 实现表单

vue 实现表单

Vue 表单实现方法 Vue.js 提供了多种方式实现表单,包括双向数据绑定、表单验证和动态表单生成。以下是常见的实现方法: 基础表单绑定 使用 v-model 指令实现表单元素与数据的双向绑定:…

vue 实现流程

vue 实现流程

Vue 实现流程 Vue.js 是一个渐进式 JavaScript 框架,用于构建用户界面。以下是 Vue 实现的基本流程: 安装 Vue.js 通过 CDN 引入或使用 npm/yarn 安装:…

vue实现组件

vue实现组件

Vue 组件实现基础 Vue 组件是可复用的 Vue 实例,用于封装 UI 和逻辑。通过 .vue 文件或直接注册组件实现。 单文件组件 (SFC) 示例 <template>…

vue  实现关联属性

vue 实现关联属性

Vue 实现关联属性 在 Vue 中实现关联属性通常涉及计算属性(computed properties)或侦听器(watchers),用于根据其他属性的变化动态更新目标属性。 使用计算属性 计算属…