var http = require("http"); var fs = require("fs"); var querystring = require("querystring"); var server = http.createServer(function (request, response) { var url = request.url; if (url === "/login") { response.writeHead(200, { "Content-type": "text/html" }) var stream = fs.createReadStream(__dirname + "/login.html", "utf-8"); stream.pipe(response); } var data = ""; request.on("error", function (err) { console.log(err) }).on("data", function (res) { data += res; }).on("end", function () { var method = request.method; console.log(method); if (method.toLowerCase() === "post") { if (method.length > 1e6) { request.connection.destroy(); } var dataobj = querystring.parse(data.toString()); var username = dataobj.username; var userpass = dataobj.userpass; if (username === "admin" && userpass === "123") { response.writeHead(200, { "Content-type": "text/html" }) var stream = fs.createReadStream(__dirname + "/home.html", "utf-8"); stream.pipe(response); } } }); }); server.listen(4000, "127.0.0.1"); server.on("error", function (e) { if (e.code == "EADDRINUSE") { console.log("in error") setTimeout(function () { server.close(); server.listen(4000, "127.0.0.1") }, 1000); } }) console.log("server has started")
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>login</title> </head> <body> <form action="/home" method="post"> <input type="text" name="username" /><br> <input type="text" name="userpass" /><br> <input type="submit" name="submit" value="提交" /> </form> </body> </html>