Node.js實現驗證登陸功能(前[html和css]後[Node.js]端交互)

說明

  1. 回顧一下Node.js一些模塊的學習

咱們首先寫好靜態頁面

  1. 爲了追求效率和美觀,咱們使用了bootstrap的bootstrap.css
  2. 驗證登陸功能咱們簡單設置一個用戶名和密碼,和一個登陸功能
  3. 結構
    靜態資源
  4. 代碼
<!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>

使用Node.js構建服務器

  1. 利用http模塊建立一個服務器
  2. 使用fs和path模塊來查看咱們的靜態頁面
  3. 注意表單的action,端口還有請求路徑保持一致
  4. 後臺部分的代碼
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...')
})
  1. 本地服務器查看頁面效果,測試靜態資源是否加載進來
    這是頁面效果
  2. 測試各個功能
  3. 解析
  • 咱們使用req.url加載靜態資源
  • 即便使用其它路徑,也會報錯

Node.js實現驗證登陸功能

  1. 導入url模塊
  2. 當點擊登陸時,獲取用戶名和密碼
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