Node.js系列——(2)發起get/post請求

服務器與瀏覽器的交互主要方式有get/post請求。
下面,咱們來看一下node.js發起get/post請求。javascript

一、get

因爲get請求的參數在url後面,因此相對比較簡單。node.js中的url模塊提供了parse函數來處理。具體代碼以下:html

//引入模塊
var http=require('http');
var url=require('url');
var util=require('util');

//建立http Server 處理請求
http.createServer(function(req,res){ res.writeHead(200,{'Content-Type': 'text/plain'});

    //解析url參數
    var params=url.parse(req.url,true).query;
    res.write('用戶名:'+params.name);
    res.write('\n');
    res.write('密碼'+params.password);
    res.end();
}).listen(8888);

測試:java

注意:上面代碼中監聽的是8888端口。
這裏寫圖片描述node

二、post

post請求的內容都包含在請求體中,所以處理起來沒有get請求那麼簡單。全部node.js 默認是不會解析請求體的,當你須要的時候,須要手動來作。c++

//引入模塊
var http=require('http');
var querystring=require('querystring');


var postHTML = 
  '<html><head><meta charset="utf-8"><title> Node.js 實例</title></head>' +
  '<body>' +
  '<form method="post">' +
  '用戶名: <input name="name"><br>' +
  '密碼: <input name="password"><br>' +
  '<input type="submit">' +
  '</form>' +
  '</body></html>'
console.log('準備html');
//建立http Server 處理請求
http.createServer(function(req,res){
    console.log('進入http Server');
    //定義post變量,暫存請求體信息
    var body='';

    //經過req的data事件監聽函數,當接收到請求體的數據,累加到post變量
    req.on('data',function(chunk){
        body+=chunk;
    });
    console.log('進入req end 1');
    //在end事件觸發後,將post解析爲真正的post請求格式
    req.on('end',function(){
        body=querystring.parse(body);
        res.writeHead(200,{'Content-Type': 'text/html; charset=utf8'});
        console.log('進入req end 2');
        if(body.name && body.password){
            res.write(body.name);
            res.write('<br>');
            res.write(body.password);
        }else{
            res.write(postHTML);
        }
        res.end();
    });
}).listen(8888);

測試:
在node終端啓動成功後,瀏覽器輸入地址http://localhost:8888,看到以下頁面:
這裏寫圖片描述web

輸入用戶名和密碼,完成回寫到瀏覽器。
這裏寫圖片描述瀏覽器

三、擴展

到此,node.js處理get和post請求的小例子就作完了。如今,應該和過去的語言對比找關係,編織知識網了。服務器

3.1模塊

每種語言都提供了必定的「基礎設施」或者叫「基礎工具」,好比java/c++的類庫。node也提供了不少模塊、函數、經常使用工具等,引入的位置在Demo的最上方,看到模塊的名字基本上就能猜到它的功能。
好比:markdown

var http=require('http');
var url=require('url');
var util=require('util');

3.2Web服務器

Web服務器的基本功能就是提供Web信息瀏覽服務。它只需支持HTTP協議、HTML文檔格式及URL,與客戶端的網絡瀏覽器配合。網絡

大體的架構邏輯是:Browser——>Web Server——>Application Server——>DB。

web服務器、客戶端實例:
須要引入http模塊,使用createServer方法建立。
注意:這裏就不詳細介紹了,只說明主要流程。

1)Server

//建立http服務器
http.createServer( function (request, response) {  
   // 解析請求,包括文件名
   var pathname = url.parse(request.url).pathname;

   // 從文件系統中讀取請求的文件內容,
   fs.readFile(pathname.substr(1), function (err, data) {

         // 響應文件內容
         response.write(data.toString());       
      }
      // 發送響應數據
      response.end();
   });   
}).listen(8081);

// 控制檯會輸出如下信息
console.log('Server running at http://127.0.0.1:8081/');

2)Client

var http = require('http');

// 封裝請求的對象
var options = {
   host: 'localhost',
   port: '8081',
   path: '/index.htm'  
};

// 處理響應的回調函數
var callback = function(response){
   // 不斷更新數據
   var body = '';
   response.on('data', function(data) {
      body += data;
   });

   response.on('end', function() {
      // 數據接收完成
      console.log(body);
   });
}
// 向服務端發送請求
var req = http.request(options, callback);
req.end();

執行server.js,

這裏寫圖片描述

而後執行client.js,而後就能夠得到index.html的內容了。

這裏寫圖片描述

相關文章
相關標籤/搜索