文章目錄
- 1. 關鍵知識點簡介
- 2. 本文最終的目錄結構
- 3. 處理GET請求
- 4. 處理POST請求
- 5. GET請求與POST請求處理的區別
- 6. 同時處理POST與GET請求
- 7. form表單實作注冊與登錄功能
- 7.1 功能點分割
- 7.2 form表單實作注冊與登錄功能效果展示
- 8. AJAX實作注冊與登錄功能
- 8.1 AJAX實作注冊與登錄功能演示效果
1. 關鍵知識點簡介
- GET請求用url模塊的parse方法決議request.url獲取引數
- POST請求用request.on監聽資料的接收,因為post資料是多段分發的,不像GET請求直接發送一段字串,post資料是異步接收的,我們必須等到post資料接收完成之后再進行處理,
2. 本文最終的目錄結構
windows、linux如何自動生成目錄結構:點擊查看
│ get.js ----------- 處理get請求
│ index.js ----------- 用戶注冊登錄驗證案例
│ post.js ----------- 處理post請求
│ postGet.js ----------- 同時處理get和post請求
│ staticServer.js ----------- 靜態服務器模塊
│
├─public ----------- 存放mime.json
│ mime.json
│
└─static ----------- 靜態檔案根目錄
form.html ----------- form表單:用戶注冊(POST方式)
form1.html ----------- form表單:用戶登錄(GET方式)
postGet.html ---------- form表單(GET和POST資料同時發送)
index.css
index.html ----------- 用戶登錄注冊首頁(ajax發送)
index.js
jquery-3.1.1.min.js
post.html ----------- post.js所需的表單
這里不會講解node靜態服務器的搭建,如果想學習請看我上一篇文章:Node之搭建靜態服務器
3. 處理GET請求
新建一個get.js檔案:
const http = require('http');
const url = require('url');
http.createServer( (req, res) => {
if(req.url === '/favicon.ico') {
res.end();
return
}
console.log("req.url === > ", req.url);
// get 資料處理
console.log(url.parse(req.url))
let {query:{a, b} } = url.parse(req.url, true);
console.log("a === ", a);
console.log("b === ", b);
res.end("{code: 0}");
}).listen(8080, ()=>{
console.log('running...');
})
node get啟動服務器,在網頁訪問 http://localhost:8080/?a=1&b=2 ,服務端列印結果如下:

可以看到,request.url是查詢字串,而url.parse(request.url)將查詢字串轉換成物件的形式,最后我們想要的是物件里邊的query屬性,因此我們用ES6的物件解構語法將引數a和引數b給解構出來,不熟悉ES6請看:ES6學習地址
因此,get資料的處理就是通過url模塊的parse方法,將字串轉換成物件,再通過query屬性拿到引數,
4. 處理POST請求
新建一個post.js檔案:
const http = require('http');
const querystring = require('querystring');
http.createServer( (req, res) => {
if(req.url === '/favicon.ico') {
res.end();
return
}
console.log("req.url === > ", req.url);
// post 資料處理
let str = '';
req.on('data', chunk => {
str += chunk //資料拼接
})
req.on('end', () => {
console.log("post資料接收完畢");
let {a, b} = querystring.parse(str);
console.log('a====>',a);
console.log('b====>',b);
})
res.end("{code: 0}");
}).listen(8080, ()=>{
console.log('running...');
})
static檔案夾下,新建一個post.html檔案,用來模擬post資料發送:
<!--body內容-->
<form method="POST" action="http://localhost:8080/index">
<div>
<input type="text" name="a">
</div>
<div>
<input type="text" name="b">
</div>
<button type="submit">提交</button>
</form>
node post啟動服務器,接著瀏覽器打開post.html,輸入內容點擊提交,將POST資料提交到剛剛運行的本地服務器里讓其進行處理:

服務端列印結果:

可以看到此時request.url里面就不包含查詢字串了,因為查詢字串被放到了請求體里,在post.js中:
- 過濾掉favicon.ico的影響
- request.on(“data”, function)的方式不斷接收分段發送的POST資料,最后將結果存放到一個變數str中
- request.on(“end”, function)的方式處理客戶端發送過來的POST請求,end表示資料已經接收完畢,接下來的處理跟GET請求的處理大同小異,只是換了個模塊而已,通過querystring模塊的parse方法將str轉換成物件,再取里面的值即可,
- response.end()方法結束請求,
5. GET請求與POST請求處理的區別
如下圖所示

6. 同時處理POST與GET請求
新建一個postGet.js檔案:
const http = require('http');
const querystring = require('querystring');
const url = require('url');
http.createServer( (req, res) => {
if(req.url === '/favicon.ico') {
res.end();
return
}
// get 資料處理
let {query:{c, d} } = url.parse(req.url, true);
console.log("c === ", c);
console.log("d === ", d);
// post 資料處理
let str = '';
req.on('data', chunk => {
str += chunk
})
req.on('end', () => {
console.log("post資料接收完畢");
// console.log("str====>", str);
let {a, b} = querystring.parse(str);
console.log('a====>',a);
console.log('b====>',b);
})
res.end("{code: 0}");
}).listen(8080, ()=>{
console.log('running...');
})
static下新建一個postGet.html檔案:
<!--body內容-->
<form method="POST" action="http://localhost:8080/index?c=111&d=222">
<div>
<input type="text" name="a">
</div>
<div>
<input type="text" name="b">
</div>
<button type="submit">提交</button>
</form>
在postGet.html里同時發送GET和POST請求,直接在form表單的action屬性添加查詢字串?c=111&d=222發送GET請求,method設定為POST發送表單資料(POST請求),
在postGet.js中,我們按照上文所講的處理方式對POST請求與GET請求進行不同的處理,
瀏覽器運行postGet.html,填寫如下內容:

點擊提交,可以看到服務端列印結果:

7. form表單實作注冊與登錄功能
新建一個處理注冊與登錄的程式入口index.js:
const http = require('http');
const querystring = require('querystring');
const path = require('path');
const url = require('url');
const staticServer = require('./staticServer');
// 模擬已注冊用戶
let user = {
zhangsan: '123456',
lisi: 'root',
}
http.createServer( (req, res) => {
if(req.url === '/favicon.ico') {
res.end();
return
}
// 處理get資料
let {pathname, query: {name, password}} = url.parse(req.url, true);
console.log('name====>',name);
console.log('password====>',password);
// 處理post資料
let data = '';
req.on('data', chunk => {
data += chunk;
})
// 資料接收完畢
req.on('end', () => {
let {name: post_name, password: post_password} = querystring.parse(data);
console.log('post_name====>', post_name);
console.log('post_password====>', post_password);
// 回應頭 主要為了解決亂碼問題
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
if(pathname === '/login'){
if(user[name] && user[name] === password){
res.end('{"code": 0, "message":"登錄成功"}');
}else {
res.end('{"code": 1, "error":"用戶名或密碼錯誤"}');
}
}else if(pathname === '/register'){
if(!post_name || !post_password){
res.end('{"code": 1, "error":"用戶名或密碼為空"}');
}else if(user[post_name]){
res.end('{"code": 1, "error":"用戶名存在"}');
}else{
res.end('{"code": 0, "message":"注冊成功"}');
// 存進用戶串列
user[post_name] = post_password;
}
}else{
staticServer(req, res, path.join(__dirname, 'static'));
}
})
}).listen(8080, () => {
console.log('running...');
})
7.1 功能點分割
- 模塊引入:
分別是http(啟動服務器)、querystring(處理POST請求)、path(靜態服務器的根目錄拼接)、url(處理GET請求)、staticServer(自定義靜態服務器模塊),
- 模擬資料庫用戶資料:
這里定義了一個user物件,存放兩個用戶(用戶名和密碼),可以模擬資料庫已經存放的資料,用于驗證,
- 決議資料:
POST請求用querystring模塊決議,GET請求用url模塊決議
- 設定回應頭:
為了防止中文亂碼,我們需要設定回應頭的編碼格式為utf8
- 根據不同行為執行不同處理:
本文定義狀態碼0為成功,1為失敗
-
如果請求路徑是/login,則進行登錄驗證處理,若用戶存在且密碼正確,則回傳成功資訊,否則發送失敗資訊,
-
如果請求路徑是/register,則進行用戶注冊,若用戶已經存在與user,則回傳用戶名已存在,注冊失敗,否則回傳注冊成功資訊,并將用戶資訊添加至user,
-
如果請求路徑并非前面兩種,則默認讓其訪問靜態服務器staticServer,成功則將靜態資料展示到網頁,失敗則回傳404頁面,
-
其他:
另一方面,細心的人可能還注意到,這里還對了post的name和password進行了重命名,這是為了防止與上面的GET的引數命名沖突,
接下來新建一個用來用戶注冊的form.html:
<!--body內容-->
<form method="POST" action="http://localhost:8080/register">
<div>
用戶名:<input type="text" name="name">
</div>
<div>
密碼:<input type="text" name="password">
</div>
<button type="submit">提交</button>
</form>
和用來用戶登錄的form1.html:
<!--body內容-->
<form method="GET" action="http://localhost:8080/login">
<div>
用戶名:<input type="text" name="name">
</div>
<div>
密碼:<input type="text" name="password">
</div>
<button type="submit">提交</button>
</form>
7.2 form表單實作注冊與登錄功能效果展示
node index啟動服務器,
首先我們先進行登錄驗證,由于在index.js中我們已經定義了一個user物件,因此我們可以將user里面的默認資料用來進行登錄驗證,首先訪問我們的首頁index.html,如下:

訪問localhost:8080/form1.html訪問登錄頁:

用戶名輸入zhangsan,密碼輸入123455,點擊登錄可以看到回傳結果:

再用一個不存在的用戶資料驗證:

接下來進行用戶注冊,訪問localhost:8080/form.html訪問注冊頁:

先注冊一個用戶名已存在的用戶,密碼任意,點擊提交,可以看到回傳結果:

然后注冊一個不存在的用戶,這里注冊用戶名wangwu,密碼123,回傳結果:

接著用我們剛注冊的用戶資訊進行登錄:

在這,我們的注冊登錄功能就已經基本實作了,接下來我們再講講ajax發送請求,
8. AJAX實作注冊與登錄功能
首先我們把靜態服務器那一章的三個靜態檔案index.html、index.js、index.css放置到靜態服務器根目錄下,傳送門, 然后修改index.html:
<body>
<h1>hello nodejs</h1>
<form>
<div>
用戶名:<input type="text" id="name">
</div>
<div>
密碼:<input type="text" id="password">
</div>
<input type="button" value="登錄" id="login"/>
<input type="button" value="注冊" id="register"/>
</form>
<script src="./index.js"></script>
<script src="./jquery-3.1.1.min.js"></script>
<script>
$('#register').on('click', () => {
$.ajax({
method: 'POST',
url: "http://localhost:8080/register",
data: {name:$("#name").val(), password:$("#password").val()},
dataType: 'json',
success:(data) => {
console.log("data====>",data);
},
error: (err) => {
console.log("err====>",err);
}
})
})
$('#login').on('click', () => {
$.ajax({
method: 'GET',
url: "http://localhost:8080/login",
data: {name:$("#name").val(), password:$("#password").val()},
dataType: 'json',
success:(data) => {
console.log("data====>",data);
},
error: (err) => {
console.log("err====>",err);
}
})
})
</script>
</body>
這里要注意form表單可有可無,而且必須將登錄和注冊按鈕的type設定成button而不是submit,不然它會發送兩次請求!一次是form表單submit的默認請求,一次是我們自定義的ajax請求,
我們設計的注冊采取的是POST請求,注冊則采用GET,因此在發送AJAX請求時要設定metho,
8.1 AJAX實作注冊與登錄功能演示效果


再輸入一個不存在的用戶名驗證錯誤資料:

接著我們注冊用戶:
首先我們輸入一個已經存在的用戶名進行注冊:

然后我們用沒注冊過的用戶名注冊,并進行登錄:

碼了7400+個字總結,肝了好多個小時,如果對您有幫助,可以一鍵三連或點個贊支持一下噢!謝謝您的支持!祝您生活愉快,幸福美滿!
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/234292.html
標籤:其他
下一篇:Qt制作安裝包程式
