<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Node實現登陸頁面</title> <link rel="stylesheet" href="css/bootstrap.css"> </head> <body> <h1 class="text-center">實現驗證登陸</h1> <div class="container"> <form method="get" action="http://localhost:3000/login.html"> <div class="form-group"> <label for="user1">用戶</label> <input type="text" class="form-control" id="user1" placeholder="輸入用戶" name="username" required> </div> <div class="form-group"> <label for="password1">密碼</label> <input type="password" class="form-control" id="password1" placeholder="輸入密碼" name="pwd" required> </div> <button type="submit" class="btn btn-primary btn-block">登陸</button> </form> </div> </body> </html>
const http = require('http') const fs = require('fs') const path = require('path') let server = http.createServer((req,res)=>{ // console.log(req.url.startsWith('/login')) // true(login) false(bootstrap) false(bootstrap) fs.readFile(path.join(__dirname,'/source',req.url),'utf8',(err,data)=>{ // 2.1 判斷文件是否存在,不存在返回404 // 2.2 最好使用req.url(這樣.css文件發送請求,req.url也能獲取到。纔會連接.css) if(err){ res.writeHead('404',{ 'Content-Type':'text/plain;charset=utf8' }) res.end('頁面不存在了') }else{ res.end(data) } }) }).listen(3000,()=>{ console.log('The Server Running...') })
const http = require('http') const fs = require('fs') const path = require('path') const {URL} = require('url') let server = http.createServer((req,res)=>{ let myURL = new URL(path.join(__dirname,req.url)) if(myURL.searchParams.get('username')){ let user = myURL.searchParams.get('username') let pwd = myURL.searchParams.get('pwd') res.writeHead('200',{ 'Content-Type':'text/plain;charset=utf8' }) res.end('你好,'+user) } fs.readFile(path.join(__dirname,'/source',req.url),'utf8',(err,data)=>{ if(err){ res.writeHead('404',{ 'Content-Type':'text/plain;charset=utf8' }) res.end('頁面不存在了') }else{ res.end(data) } }) }).listen(3000,()=>{ console.log('The Server Running...') })
// 1.構建web服務器
// 2.渲染頁面
// 2.1 判斷頁面是否存在
// 2.2 不是的話返回404
// 2.3 是的話,讀取文件並渲染到頁面上
// 3.登陸後獲取用戶名和密碼
// 3.1 點擊登陸按鈕會從新發送請求
// 3.2 此時能拿到用戶名和密碼,但要處理下
// 3.1 獲取url地址的searchParams的用戶名和密碼
// 4. 實現登陸
// 4.1 返回新頁面css