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

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

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

app.js

javascript 复制代码
// 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

javascript 复制代码
// 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

javascript 复制代码
// 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 -->

javascript 复制代码
<!-- 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 -->

javascript 复制代码
<!-- 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

javascript 复制代码
// 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

javascript 复制代码
<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

javascript 复制代码
// 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');

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

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

相关推荐
cs_dn_Jie14 分钟前
钉钉 H5 微应用 手机端调试
前端·javascript·vue.js·vue·钉钉
开心工作室_kaic1 小时前
ssm068海鲜自助餐厅系统+vue(论文+源码)_kaic
前端·javascript·vue.js
有梦想的刺儿1 小时前
webWorker基本用法
前端·javascript·vue.js
Ai 编码助手1 小时前
MySQL中distinct与group by之间的性能进行比较
数据库·mysql
陈燚_重生之又为程序员1 小时前
基于梧桐数据库的实时数据分析解决方案
数据库·数据挖掘·数据分析
caridle1 小时前
教程:使用 InterBase Express 访问数据库(五):TIBTransaction
java·数据库·express
cy玩具1 小时前
点击评论详情,跳到评论页面,携带对象参数写法:
前端
白云如幻1 小时前
MySQL排序查询
数据库·mysql
萧鼎2 小时前
Python并发编程库:Asyncio的异步编程实战
开发语言·数据库·python·异步
^velpro^2 小时前
数据库连接池的创建
java·开发语言·数据库