Skip to content

Commit

Permalink
[Feat] Modular Routing
Browse files Browse the repository at this point in the history
  • Loading branch information
immengzi committed Mar 22, 2024
1 parent c98ddee commit 1a979da
Show file tree
Hide file tree
Showing 6 changed files with 89 additions and 65 deletions.
59 changes: 4 additions & 55 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,69 +11,18 @@ app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`)
})

const bcrypt = require('bcrypt')
const db = require('./db')

app.use(express.static('./static'))
app.use(cookieSession({
name: 'session',
keys: ['key1', 'key2'],
maxAge: 24 * 60 * 60 * 1000 // 24 hours
}))

app.get('/get-user-info', (req, res) => {
if (req.session.email) {
res.status(200).send({email: req.session.email, username: req.session.username})
} else {
res.status(401).json({ message: "用户未登录" });
}
})

app.post('/register', async (req, res) => {
const {email, username, password} = req.body
const hashedPassword = await bcrypt.hash(password, 10)
const user = require('./routes/user')
app.use("/user", user)

const result = await db.createUser({email, username, password: hashedPassword})
res.status(200).send(result)
console.log("注册成功")
})

app.post('/login', async (req, res) => {
const {email, password} = req.body
const user = await db.findUserByEmail(email)

if (user && await bcrypt.compare(password, user.password)) {
req.session.email = user.email
req.session.username = user.username
console.log(`${user.username}登录成功`)
res.status(200).send({message: `${user.username}登录成功`})
} else {
res.status(401).send({error: "Email or password is incorrect"})
}
})

app.get('/logout', (req, res) => {
req.session = null;
res.send({ message: '已成功注销' });
});

// 留言板帖子的CRUD路由

app.get('/get-posts', async (req, res) => {
const posts = await db.getPosts()
res.status(200).send(posts)
})

app.post('/submit', async (req, res) => {
const {email, message} = req.body;
try {
const result = await db.createPost({user_email: email, content: message});
res.status(200).send(result);
} catch (error) {
console.error(error);
res.status(500).send('Error creating post');
}
})
const post = require('./routes/post')
app.use("/post", post)

app.use((req, res) => {
res.status(404).send("Sorry can't find that!")
Expand Down
20 changes: 16 additions & 4 deletions db.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ let db = new sqlite3.Database(dbPath, sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREA
if (err) {
console.error(err.message)
}
console.log('Connected to the hjl_site.db database.')
console.log('Connected to the database.')
})

const initDb = () => {
Expand All @@ -15,16 +15,28 @@ const initDb = () => {
email TEXT NOT NULL UNIQUE,
username TEXT NOT NULL UNIQUE,
password TEXT NOT NULL
)`);
)`,(err) => {
if (err) {
console.error(err.message)
} else {
console.log('Table users created or already exists.')
}
})

db.run(`CREATE TABLE IF NOT EXISTS posts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_email TEXT NOT NULL,
content TEXT NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_email) REFERENCES users(email)
)`);
};
)`,(err) => {
if (err) {
console.error(err.message)
} else {
console.log('Table posts created or already exists.')
}
})
}

initDb();

Expand Down
Binary file modified hjl_site.db
Binary file not shown.
21 changes: 21 additions & 0 deletions routes/post.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
const express = require("express")
const db = require('../db')
const router = express.Router()

router.get('/get-posts', async (req, res) => {
const posts = await db.getPosts()
res.status(200).send(posts)
})

router.post('/submit', async (req, res) => {
const {email, message} = req.body;
try {
const result = await db.createPost({user_email: email, content: message});
res.status(200).send(result);
} catch (error) {
console.error(error);
res.status(500).send('Error creating post');
}
})

module.exports = router
42 changes: 42 additions & 0 deletions routes/user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
const express = require("express")
const bcrypt = require('bcrypt')
const db = require('../db')
const router = express.Router()

router.get('/get-user-info', (req, res) => {
if (req.session.email) {
res.status(200).send({email: req.session.email, username: req.session.username})
} else {
res.status(401).json({ message: "用户未登录" });
}
})

router.post('/register', async (req, res) => {
const {email, username, password} = req.body
const hashedPassword = await bcrypt.hash(password, 10)

const result = await db.createUser({email, username, password: hashedPassword})
res.status(200).send(result)
console.log("注册成功")
})

router.post('/login', async (req, res) => {
const {email, password} = req.body
const user = await db.findUserByEmail(email)

if (user && await bcrypt.compare(password, user.password)) {
req.session.email = user.email
req.session.username = user.username
console.log(`${user.username}登录成功`)
res.status(200).send({message: `${user.username}登录成功`})
} else {
res.status(401).send({error: "Email or password is incorrect"})
}
})

router.get('/logout', (req, res) => {
req.session = null
res.send({ message: '已成功注销' })
})

module.exports = router
12 changes: 6 additions & 6 deletions static/sea.html
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ <h5 class="card-title">留言标题</h5>
let loginLink = document.getElementById('loginLink')
let logoutLink = document.getElementById('logoutLink')

fetch('/get-user-info')
fetch('/user/get-user-info')
.then(response => {
if (response.status === 200) return response.json()
else throw new Error('用户未登录')
Expand Down Expand Up @@ -165,7 +165,7 @@ <h5 class="card-title">留言标题</h5>
return
}

fetch('/register', {
fetch('/user/register', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
Expand Down Expand Up @@ -194,7 +194,7 @@ <h5 class="card-title">留言标题</h5>
return
}

fetch('/login', {
fetch('/user/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
Expand All @@ -221,7 +221,7 @@ <h5 class="card-title">留言标题</h5>
}

function logout() {
fetch('/logout')
fetch('/user/logout')
.then(response => {
if (response.status === 200) {
console.log("退出成功")
Expand All @@ -243,7 +243,7 @@ <h5 class="card-title">留言标题</h5>
}

function showPosts() {
fetch('/get-posts')
fetch('/post/get-posts')
.then(response => {
if (response.status === 200) return response.json()
else throw new Error('获取留言失败')
Expand Down Expand Up @@ -290,7 +290,7 @@ <h5 class="card-title">留言标题</h5>
alert('请填写留言内容')
return
}
fetch('/submit', {
fetch('/post/submit', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
Expand Down

0 comments on commit 1a979da

Please sign in to comment.