在上一篇的基础上我有添加了登录注册功能文件上传
更新一下代码添加登录注册功能
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');
记得安装对应的包和更新依赖!!!
请记得一键三连(点赞、收藏、分享)哦!