当前位置: 首页 > news >正文

注册登录后上传文件到本地数据库项目

        在上一篇的基础上我有添加了登录注册功能文件上传

更新一下代码添加登录注册功能

app.js

// app.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const db = require('./models/db');
const User = require('./models/userModel');
const File = require('./models/fileModel');
const uploadRoutes = require('./routes/upload');
const authRoutes = require('./routes/auth');const app = express();
const PORT = 5000;// 中间件
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));// 路由
app.use('/upload', uploadRoutes);
app.use('/auth', authRoutes);// 同步数据库
db.sync().then(() => {console.log('数据库连接成功...');
}).catch(err => console.log('错误: ' + err));app.listen(PORT, () => {console.log(`服务器正在运行在 http://localhost:${PORT}`);
});

 // routes/auth.js

// routes/auth.js
const express = require('express');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const User = require('../models/userModel');const router = express.Router();
const secret = 'your_jwt_secret';// 用户注册
router.post('/register', async (req, res) => {try {const { username, password } = req.body;const hashedPassword = await bcrypt.hash(password, 10);const newUser = await User.create({ username, password: hashedPassword });res.status(201).json({ message: '用户注册成功', user: newUser });} catch (error) {res.status(500).json({ message: '注册失败', error });}
});// 用户登录
router.post('/login', async (req, res) => {try {const { username, password } = req.body;const user = await User.findOne({ where: { username } });if (!user) {return res.status(404).json({ message: '用户不存在' });}const isPasswordValid = await bcrypt.compare(password, user.password);if (!isPasswordValid) {return res.status(401).json({ message: '密码错误' });}const token = jwt.sign({ userId: user.id }, secret, { expiresIn: '1h' });res.status(200).json({ message: '登录成功', token });} catch (error) {res.status(500).json({ message: '登录失败', error });}
});module.exports = router;

 // models/userModel.js

// models/userModel.js
const { Sequelize, DataTypes } = require('sequelize');
const db = require('./db');const User = db.define('User', {username: {type: DataTypes.STRING,allowNull: false,unique: true},password: {type: DataTypes.STRING,allowNull: false}
});module.exports = User;

 <!-- src/components/Login.vue -->

<!-- src/components/Login.vue -->
<template><div><h2>用户登录</h2><form @submit.prevent="login"><div><label for="username">用户名:</label><input type="text" id="username" v-model="username" required /></div><div><label for="password">密码:</label><input type="password" id="password" v-model="password" required /></div><button type="submit">登录</button></form></div>
</template><script>
export default {data() {return {username: '',password: ''};},methods: {async login() {try {const response = await fetch('http://localhost:5000/auth/login', {method: 'POST',headers: {'Content-Type': 'application/json'},body: JSON.stringify({ username: this.username, password: this.password })});const data = await response.json();if (response.ok) {localStorage.setItem('token', data.token);alert('登录成功!');this.$router.push('/upload');} else {alert('登录失败:' + data.message);}} catch (error) {alert('登录失败:' + error.message);}}}
};
</script>

 <!-- src/components/Register.vue -->

<!-- src/components/Register.vue -->
<template><div><h2>用户注册</h2><form @submit.prevent="register"><div><label for="username">用户名:</label><input type="text" id="username" v-model="username" required /></div><div><label for="password">密码:</label><input type="password" id="password" v-model="password" required /></div><button type="submit">注册</button></form></div>
</template><script>
export default {data() {return {username: '',password: ''};},methods: {async register() {try {const response = await fetch('http://localhost:5000/auth/register', {method: 'POST',headers: {'Content-Type': 'application/json'},body: JSON.stringify({ username: this.username, password: this.password })});const data = await response.json();if (response.ok) {alert('注册成功!');} else {alert('注册失败:' + data.message);}} catch (error) {alert('注册失败:' + error.message);}}}
};
</script>

// src/router/index.js 

// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router';
import Register from '../components/Register.vue';
import Login from '../components/Login.vue';
import FileUpload from '../components/FileUpload.vue';const routes = [{ path: '/register', component: Register },{ path: '/login', component: Login },{ path: '/upload', component: FileUpload, meta: { requiresAuth: true } }
];const router = createRouter({history: createWebHistory(),routes
});// 导航守卫
router.beforeEach((to, from, next) => {const loggedIn = localStorage.getItem('user');if (to.matched.some(record => record.meta.requiresAuth) && !loggedIn) {next('/login');} else {next();}
});export default router;

 app.vue

<template><div id="app"><header><h1>我的应用</h1><nav v-if="!loggedIn"><ul><li @click="goTo('/login')">登录</li><li @click="goTo('/register')">注册</li></ul></nav><nav v-else><ul><li @click="goTo('/upload')">文件上传</li><li @click="logout">退出</li></ul></nav></header><main><router-view></router-view></main></div>
</template><script>
export default {data() {return {loggedIn: false};},created() {// 检查本地存储中是否有用户登录信息const token = localStorage.getItem('token');if (token) {this.loggedIn = true;}},methods: {goTo(path) {this.$router.push(path);},logout() {localStorage.removeItem('token');this.loggedIn = false;this.$router.push('/login');}}
};
</script><style>
#app {font-family: Avenir, Helvetica, Arial, sans-serif;text-align: center;color: #2c3e50;margin-top: 60px;
}header {background-color: #35495e;padding: 10px 0;color: white;
}nav ul {list-style: none;padding: 0;
}nav ul li {display: inline;margin: 0 10px;cursor: pointer;
}
</style>

 // src/main.js

// src/main.js
import { createApp } from 'vue';
import App from './App.vue';
import { createRouter, createWebHistory } from 'vue-router';
import Register from './components/Register.vue';
import Login from './components/Login.vue';
import FileUpload from './components/FileUpload.vue';const routes = [{ path: '/register', component: Register },{ path: '/login', component: Login },{ path: '/upload', component: FileUpload }
];const router = createRouter({history: createWebHistory(),routes
});const app = createApp(App);
app.use(router);
app.mount('#app');

记得安装对应的包和更新依赖!!!

请记得一键三连(点赞、收藏、分享)哦!

相关文章:

注册登录后上传文件到本地数据库项目

在上一篇的基础上我有添加了登录注册功能文件上传 更新一下代码添加登录注册功能 app.js // app.js const express require(express); const bodyParser require(body-parser); const cors require(cors); const db require(./models/db); const User require(./models…...

【学习笔记】无人机(UAV)在3GPP系统中的增强支持(十三)-更换无人机控制器

引言 本文是3GPP TR 22.829 V17.1.0技术报告&#xff0c;专注于无人机&#xff08;UAV&#xff09;在3GPP系统中的增强支持。文章提出了多个无人机应用场景&#xff0c;分析了相应的能力要求&#xff0c;并建议了新的服务级别要求和关键性能指标&#xff08;KPIs&#xff09;。…...

react 组件通信 —— 父子传值 【 函数式/类式 】

1、函数式组件通信 父子间通信 —— 父传子 父组件 export default function father() {return (<div style{{width:400px,height:200px,background:pink,marginLeft:500px}}>我是父组件<hr /><Son name{"韩小刀"}/></div>) } 子组件 ex…...

【SpringBoot】95、SpringBoot中使用MyBatis-Plus实现自动加密存储和查询自动解密

有的业务需要将敏感数据加密存储到 DB,如果我们每个都手动去加密,再设值,再保存 DB,不仅麻烦,还对开发者不友好,在 MyBatis-Plus 中我们可以使用 BaseTypeHandler 来解决这个问题 1、新增 TypeHandler import com.baomidou.mybatisplus.core.toolkit.AES; import com.b…...

[数仓]十二、离线数仓(Atlas元数据管理)

第1章 Atlas入门 1.1 Atlas概述 Apache Atlas为组织提供开放式元数据管理和治理功能,用以构建其数据资产目录,对这些资产进行分类和管理,并为数据分析师和数据治理团队,提供围绕这些数据资产的协作功能。 Atlas的具体功能如下: 元数据分类 支持对元数据进行分类管理,例…...

机器学习——决策树(笔记)

目录 一、认识决策树 1. 介绍 2. 决策树生成过程 二、sklearn中的决策树 1. tree.DecisionTreeClassifier&#xff08;分类树&#xff09; &#xff08;1&#xff09;模型基本参数 &#xff08;2&#xff09;模型属性 &#xff08;3&#xff09;接口 2. tree.Decision…...

翁恺-C语言程序设计-08-1. 求一批整数中出现最多的个位数字

08-1. 求一批整数中出现最多的个位数字 给定一批整数&#xff0c;分析每个整数的每一位数字&#xff0c;求出现次数最多的个位数字。例如给定3个整数1234、2345、3456&#xff0c;其中出现最多次数的数字是3和4&#xff0c;均出现了3次。 输入格式&#xff1a; 输入在第1行中…...

ROM修改进阶教程------深度解析小米设备锁机型不解锁bl 刷写特殊类固件的步骤

在玩机过程中会遇到很多自己机型忘记密码或者手机号不用导致机型出现账号锁。无法正常使用。那么此类机型如果无法正常售后解锁。只能通过第三方渠道。例如在早期小米机型有强解bl锁资源。然后刷入完美解锁包。这种可以登陆新账号。但后期新机型只能通过修改分区来屏蔽原设备锁…...

论文翻译 | LEAST-TO-MOST: 从最少到最多的提示使大型语言模型中的复杂推理成为可能

摘要 思维链提示&#xff08;Chain-of-thought prompting&#xff09;在多种自然语言推理任务上展现了卓越的性能。然而&#xff0c;在需要解决的问题比提示中展示的示例更难的任务上&#xff0c;它的表现往往不佳。为了克服从简单到困难的泛化挑战&#xff0c;我们提出了一种新…...

【区块链 + 智慧政务】都江堰区块链公共服务应用平台 | FISCO BCOS应用案例

都江堰区块链公共服务应用平台是四川开源观科技有限公司运用 FISCO BCOS 区块链技术为都江堰市建设的市级 区块链节点平台&#xff0c;该平台上线运营一年以来已在政务服务、社区养老和慈善公益领域落地 3 个应用&#xff0c;上链数据超 过 30 万条。 区块链 政务服务应用&am…...

Python从0到100(三十九):数据提取之正则(文末免费送书)

前言&#xff1a; 零基础学Python&#xff1a;Python从0到100最新最全教程。 想做这件事情很久了&#xff0c;这次我更新了自己所写过的所有博客&#xff0c;汇集成了Python从0到100&#xff0c;共一百节课&#xff0c;帮助大家一个月时间里从零基础到学习Python基础语法、Pyth…...

redis redisson(仅供自己参考)

redis 通过setnx实现的分布式锁有问题 如图&#xff1a; 解决的新的工具为&#xff08;闪亮登场&#xff09;&#xff1a;redisson redisson可重入锁的原理 实现语言lua&#xff1a; 加锁实现脚本语言&#xff1a; 释放锁的脚本语言&#xff1a; 加锁的lua -- 首先判断这个锁…...

【C语言初阶】探索编程基础:深入理解分支与循环语句的奥秘

&#x1f4dd;个人主页&#x1f339;&#xff1a;Eternity._ ⏩收录专栏⏪&#xff1a;C语言 “ 登神长阶 ” &#x1f921;往期回顾&#x1f921;&#xff1a;C语言入门 &#x1f339;&#x1f339;期待您的关注 &#x1f339;&#x1f339; ❀分支与循环语句 &#x1f4d2;1.…...

ERP基础知识

ERP 一、概述 ​ ERP是Event-related Potentials的简称。外加一种特定的刺激&#xff0c;作用于感觉系统或脑 的某一部位&#xff0c;在给予刺激或撤销刺激时&#xff0c;或和当某种心理因素出现时在脑区所产生的电位变化&#xff0c;成为事件相关电位&#xff0c;是一种特殊…...

C++是否可以使用.获取union、struct中的成员变量的地址

C可以使用.获取union、struct中的成员变量的地址 示例代码如下所示 #include <stdio.h> #include <stdint.h>struct u128 { uint64_t v64; uint64_t v0; };int main() {union { unsigned __int128 ui; struct u128 s; } union_temp_m128;void* p1 &union_te…...

【前端】包管理器:npm、Yarn 和 pnpm 的全面比较

前端开发中的包管理器&#xff1a;npm、Yarn 和 pnpm 的全面比较 在现代前端开发中&#xff0c;包管理器是开发者必不可少的工具。它们不仅能帮我们管理项目的依赖&#xff0c;还能极大地提高开发效率。本文将详细介绍三种主流的前端包管理器&#xff1a;npm、Yarn 和 pnpm&am…...

C++ 类和对象 赋值运算符重载

前言&#xff1a; 在上文我们知道数据类型分为自定义类型和内置类型&#xff0c;当我想用内置类型比较大小是非常容易的但是在C中成员变量都是在类(自定义类型)里面的&#xff0c;那我想给类比较大小那该怎么办呢&#xff1f;这时候运算符重载就出现了 一 运算符重载概念&…...

【Python实战因果推断】35_双重差分6

目录 Strict Exogeneity No Time Varying Confounders No Feedback No Carryover and No Lagged Dependent Variable Strict Exogeneity 严格的外生性假设是一个相当技术性的假设&#xff0c;通常用固定效应模型的残差来表示&#xff1a; 严格的异质性说明&#xff1a; 这…...

【HarmonyOS】关于官方推荐的组件级路由Navigation的心得体会

前言 最近因为之前的630版本有点忙&#xff0c;导致断更了几天&#xff0c;现在再补上。换换脑子。 目前内测系统的华为应用市场&#xff0c;各种顶级APP陆续都放出来beta版本了&#xff0c;大体上都完成了主流程的开发。欣欣向荣的气息。 学习思路 关于学习HarmonyOS的问题…...

Spring中事件监听器

实现ApplicationListener接口 Configuration public class A48 {public static void main(String[] args) {AnnotationConfigApplicationContext context new AnnotationConfigApplicationContext(A48.class);context.getBean(MyService.class).doBusiness();context.close()…...

java调用dll出现unsatisfiedLinkError以及JNA和JNI的区别

UnsatisfiedLinkError 在对接硬件设备中&#xff0c;我们会遇到使用 java 调用 dll文件 的情况&#xff0c;此时大概率出现UnsatisfiedLinkError链接错误&#xff0c;原因可能有如下几种 类名错误包名错误方法名参数错误使用 JNI 协议调用&#xff0c;结果 dll 未实现 JNI 协…...

【论文笔记】若干矿井粉尘检测算法概述

总的来说&#xff0c;传统机器学习、传统机器学习与深度学习的结合、LSTM等算法所需要的数据集来源于矿井传感器测量的粉尘浓度&#xff0c;通过建立回归模型来预测未来矿井的粉尘浓度。传统机器学习算法性能易受数据中极端值的影响。YOLO等计算机视觉算法所需要的数据集来源于…...

Nginx server_name 配置说明

Nginx 是一个高性能的反向代理和负载均衡服务器&#xff0c;其核心配置之一是 server 块中的 server_name 指令。server_name 决定了 Nginx 如何根据客户端请求的 Host 头匹配对应的虚拟主机&#xff08;Virtual Host&#xff09;。 1. 简介 Nginx 使用 server_name 指令来确定…...

【Oracle】分区表

个人主页&#xff1a;Guiat 归属专栏&#xff1a;Oracle 文章目录 1. 分区表基础概述1.1 分区表的概念与优势1.2 分区类型概览1.3 分区表的工作原理 2. 范围分区 (RANGE Partitioning)2.1 基础范围分区2.1.1 按日期范围分区2.1.2 按数值范围分区 2.2 间隔分区 (INTERVAL Partit…...

学校时钟系统,标准考场时钟系统,AI亮相2025高考,赛思时钟系统为教育公平筑起“精准防线”

2025年#高考 将在近日拉开帷幕&#xff0c;#AI 监考一度冲上热搜。当AI深度融入高考&#xff0c;#时间同步 不再是辅助功能&#xff0c;而是决定AI监考系统成败的“生命线”。 AI亮相2025高考&#xff0c;40种异常行为0.5秒精准识别 2025年高考即将拉开帷幕&#xff0c;江西、…...

使用Matplotlib创建炫酷的3D散点图:数据可视化的新维度

文章目录 基础实现代码代码解析进阶技巧1. 自定义点的大小和颜色2. 添加图例和样式美化3. 真实数据应用示例实用技巧与注意事项完整示例(带样式)应用场景在数据科学和可视化领域,三维图形能为我们提供更丰富的数据洞察。本文将手把手教你如何使用Python的Matplotlib库创建引…...

Yolov8 目标检测蒸馏学习记录

yolov8系列模型蒸馏基本流程&#xff0c;代码下载&#xff1a;这里本人提交了一个demo:djdll/Yolov8_Distillation: Yolov8轻量化_蒸馏代码实现 在轻量化模型设计中&#xff0c;**知识蒸馏&#xff08;Knowledge Distillation&#xff09;**被广泛应用&#xff0c;作为提升模型…...

【MATLAB代码】基于最大相关熵准则(MCC)的三维鲁棒卡尔曼滤波算法(MCC-KF),附源代码|订阅专栏后可直接查看

文章所述的代码实现了基于最大相关熵准则(MCC)的三维鲁棒卡尔曼滤波算法(MCC-KF),针对传感器观测数据中存在的脉冲型异常噪声问题,通过非线性加权机制提升滤波器的抗干扰能力。代码通过对比传统KF与MCC-KF在含异常值场景下的表现,验证了后者在状态估计鲁棒性方面的显著优…...

为什么要创建 Vue 实例

核心原因:Vue 需要一个「控制中心」来驱动整个应用 你可以把 Vue 实例想象成你应用的**「大脑」或「引擎」。它负责协调模板、数据、逻辑和行为,将它们变成一个活的、可交互的应用**。没有这个实例,你的代码只是一堆静态的 HTML、JavaScript 变量和函数,无法「活」起来。 …...

SpringAI实战:ChatModel智能对话全解

一、引言&#xff1a;Spring AI 与 Chat Model 的核心价值 &#x1f680; 在 Java 生态中集成大模型能力&#xff0c;Spring AI 提供了高效的解决方案 &#x1f916;。其中 Chat Model 作为核心交互组件&#xff0c;通过标准化接口简化了与大语言模型&#xff08;LLM&#xff0…...