今天我們來實作登入畫面,我會先預設一個登入畫面,可以輸入帳號密碼,輸入正確後會顯示登入成功,否則會跳轉至失敗,以下為程式碼:
const http = require("http");
const fs = require("fs");
const path = require("path");
const qs = require("querystring");
const port = 3000;
const ip = "127.0.0.1";
const sendResponse = (filename, statusCode, response) => {
const filePath = path.join(__dirname, filename);
fs.readFile(filePath, (error, data) => {
if (error) {
console.error(`Error reading file: ${filename}`);
console.error(error);
response.statusCode = 500;
response.setHeader("Content-Type", "text/plain");
response.end("Sorry, internal error");
} else {
response.statusCode = statusCode;
response.setHeader("Content-Type", "text/html");
response.end(data);
}
});
};
const server = http.createServer((request, response) => {
const method = request.method;
const url = request.url;
if (method === "GET") {
if (url === "/") {
sendResponse("login.html", 200, response);
} else if (url === "/success.html") {
sendResponse("success.html", 200, response);
} else if (url === "/fail.html") {
sendResponse("fail.html", 200, response);
} else {
sendResponse("404.html", 404, response);
}
} else if (method === "POST" && url === "/process-login") {
let body = "";
request.on("data", (chunk) => {
body += chunk.toString();
});
request.on("end", () => {
const formData = qs.parse(body);
if (formData.username.toLowerCase() === "aaa" && formData.password === "123456") {
response.writeHead(302, {
Location: "/success.html"
});
response.end();
} else {
response.writeHead(302, {
Location: "/fail.html"
});
response.end();
}
});
} else {
sendResponse("404.html", 404, response);
}
});
server.listen(port, ip, () => {
console.log(`Server is running at http://${ip}:${port}`);
});
這是node.js的主要程式碼,其餘html的三個文件就簡單地做分別,不過我的登入結果還有一點問題需要處理,我將修正它以及詳細講解。