当前位置:首页 > 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创建前端页面,实现用户注册和登录功能。

安装依赖

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中间件处理跨域请求,确保前后端可以正常通信。

node vue实现 登录注册

标签: nodevue
分享给朋友:

相关文章

vue实现飘窗原理

vue实现飘窗原理

vue实现飘窗原理 飘窗效果通常指在页面上悬浮显示的弹窗或通知,跟随页面滚动或固定在某个位置。Vue实现这一效果主要依赖组件化开发、CSS定位和动态数据绑定。 组件结构设计 创建一个独立的Vue组…

vue实现双折线图

vue实现双折线图

实现双折线图的步骤 安装必要的依赖库(如 ECharts 或 Chart.js),这里以 ECharts 为例: npm install echarts --save 在 Vue 组件中引入 EC…

vue实现选中单元格

vue实现选中单元格

Vue 实现选中单元格的方法 基础实现思路 在 Vue 中实现选中单元格功能,通常可以通过动态绑定 class 或 style 来实现。以下是一个基于表格的简单实现示例: <templ…

vue实现mvc

vue实现mvc

Vue 实现 MVC 模式 Vue 本身是一个 MVVM(Model-View-ViewModel)框架,但可以通过结构调整实现 MVC(Model-View-Controller)模式。以下是具体实…

vue实现https

vue实现https

Vue 中实现 HTTPS 的步骤 在 Vue 项目中实现 HTTPS 主要涉及开发环境配置和生产环境部署。以下是具体方法: 开发环境配置(Vue CLI 或 Vite) 使用 mkcert 生成…

vue实现handsontable

vue实现handsontable

Vue 中实现 Handsontable 要在 Vue 项目中集成 Handsontable,可以使用官方提供的 @handsontable/vue 封装库。以下是一个完整的实现步骤。 安装依赖 确…