Node之處理Get與Post請求

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中:



  1. 過濾掉favicon.ico的影響
  2. request.on(“data”, function)的方式不斷接收分段發送的POST數據,最後將結果存放到一個變量str
  3. request.on(“end”, function)的方式處理客戶端發送過來的POST請求end表示數據已經接收完畢。接下來的處理跟GET請求的處理大同小異,只是換了個模塊而已,通過querystring模塊的parse方法將str轉換成對象,再取裏面的值即可。
  4. 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+個字總結,肝了好多個小時,如果對您有幫助,可以一鍵三連或點個贊支持一下噢!謝謝您的支持!祝您生活愉快,幸福美滿!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章