feat(server.tests.test6): 新增 nodejs 实验 6

This commit is contained in:
2025-11-25 11:21:14 +08:00
parent 6a08063952
commit 65d3c97e60
4 changed files with 127 additions and 0 deletions

View File

@@ -0,0 +1,54 @@
const express = require("express");
const session = require("express-session");
const bodyParser = require("body-parser");
const app = express();
const port = 3000;
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use(session({
secret: "hello kitty",
resave: false,
saveUninitialized: true,
cookie: { secret: false }
}))
const isAuthenticated = (req, res, next) => {
if (req.session.user)
next();
else
res.status(401).send("You are not authenticated!");
}
app.post("/login", (req, res) => {
const { username, password } = req.body;
if (username === "admin" && password === "password") {
req.session.user = { id: 1, username };
res.send("User logged in");
} else {
res.status(401).send("Invaild credentials");
}
})
app.post("/logout", (req, res) => {
req.session.destroy((error) => {
if (error)
return res.status(500).send("Could not log out.");
res.send("Logout successful")
})
})
app.get("/protected", isAuthenticated, (req, res) => {
res.send("This is a protected route");
})
app.get("/profile", isAuthenticated, (req, res) => {
res.send(`Welcome ${req.session.user.username}`);
})
app.listen(port, (error) => {
if (error)
console.log(error);
console.log(`server is running: http://localhost:${port}`);
})