当前位置:首页 > VUE

vue node实现登录验证

2026-02-23 16:55:44VUE

Vue 和 Node.js 实现登录验证

前端部分 (Vue)

安装必要的依赖,如 axios 用于发送 HTTP 请求:

npm install axios

创建登录表单组件,包含用户名和密码输入框:

<template>
  <form @submit.prevent="handleLogin">
    <input v-model="username" type="text" placeholder="Username">
    <input v-model="password" type="password" placeholder="Password">
    <button type="submit">Login</button>
  </form>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      username: '',
      password: ''
    }
  },
  methods: {
    async handleLogin() {
      try {
        const response = await axios.post('http://localhost:3000/login', {
          username: this.username,
          password: this.password
        });
        localStorage.setItem('token', response.data.token);
        this.$router.push('/dashboard');
      } catch (error) {
        console.error('Login failed:', error);
      }
    }
  }
}
</script>

后端部分 (Node.js)

安装必要的依赖:

npm install express body-parser jsonwebtoken bcryptjs

创建 Express 服务器并设置路由:

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

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

const users = []; // 临时存储用户数据,实际项目中应使用数据库

app.post('/register', async (req, res) => {
  try {
    const hashedPassword = await bcrypt.hash(req.body.password, 10);
    const user = { username: req.body.username, password: hashedPassword };
    users.push(user);
    res.status(201).send();
  } catch {
    res.status(500).send();
  }
});

app.post('/login', async (req, res) => {
  const user = users.find(user => user.username === req.body.username);
  if (user == null) return res.status(400).send('Cannot find user');

  try {
    if (await bcrypt.compare(req.body.password, user.password)) {
      const token = jwt.sign({ username: user.username }, 'secret_key');
      res.json({ token });
    } else {
      res.status(403).send('Not Allowed');
    }
  } catch {
    res.status(500).send();
  }
});

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

验证保护路由

在前端添加路由守卫:

// router.js
import Vue from 'vue';
import Router from 'vue-router';
import Dashboard from './views/Dashboard.vue';
import Login from './views/Login.vue';

Vue.use(Router);

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

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;

在后端添加中间件验证 JWT:

function authenticateToken(req, res, next) {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];

  if (token == null) return res.sendStatus(401);

  jwt.verify(token, 'secret_key', (err, user) => {
    if (err) return res.sendStatus(403);
    req.user = user;
    next();
  });
}

app.get('/protected', authenticateToken, (req, res) => {
  res.json({ message: 'Protected data', user: req.user });
});

密码加密

使用 bcrypt 对密码进行加密存储:

const saltRounds = 10;
const hashedPassword = await bcrypt.hash(plainPassword, saltRounds);

令牌刷新

实现令牌刷新机制:

app.post('/token', (req, res) => {
  const refreshToken = req.body.token;
  if (refreshToken == null) return res.sendStatus(401);

  jwt.verify(refreshToken, 'refresh_secret', (err, user) => {
    if (err) return res.sendStatus(403);
    const accessToken = jwt.sign({ username: user.username }, 'secret_key', { expiresIn: '15m' });
    res.json({ accessToken });
  });
});

跨域问题解决

在 Node.js 中启用 CORS:

const cors = require('cors');
app.use(cors());

或在 Vue 中配置代理:

// vue.config.js
module.exports = {
  devServer: {
    proxy: 'http://localhost:3000'
  }
}

vue node实现登录验证

标签: vuenode
分享给朋友:

相关文章

vue实现中台

vue实现中台

Vue 实现中台系统的关键步骤 技术选型与基础搭建 使用 Vue 3(Composition API)或 Vue 2(Options API)作为前端框架,搭配 Vue Router 实现路由管理,V…

vue实现通知

vue实现通知

Vue 实现通知功能的方法 使用 Vue 实现通知功能可以通过多种方式实现,以下是一些常见的方法: 使用 Vue 的全局事件总线 在 Vue 中可以通过事件总线实现通知功能。创建一个全局事件总线,…

vue compile 实现

vue compile 实现

Vue 编译实现原理 Vue 的编译过程将模板字符串转换为渲染函数,主要分为解析、优化和代码生成三个阶段。 解析阶段(Parse) 将模板字符串转换为抽象语法树(AST)。Vue 使用正则表达式和有…

vue实现toast

vue实现toast

Vue 实现 Toast 的方法 使用第三方库(推荐) 对于快速实现 Toast 功能,推荐使用成熟的第三方库如 vue-toastification 或 vant 的 Toast 组件。 安装 v…

vue实现开关

vue实现开关

Vue 实现开关组件的方法 使用原生HTML和Vue数据绑定 通过v-model绑定复选框的checked状态,结合CSS样式实现开关效果: <template> <labe…

vue实现slidetoggle

vue实现slidetoggle

Vue 实现 SlideToggle 效果 SlideToggle 是一种常见的交互效果,元素以滑动方式展开或收起。以下是几种实现方法: 使用 CSS Transition 和 v-show 通过…