前言
我們知道傳統的HTPP服務器會由Aphche、Nginx、IIS之類的軟件來擔任,但是nodejs并不需要,nodejs提供了http模塊,自身就可以用來構建服務器,而且http模塊是由C++實現的,性能可靠。其中封裝了一個高校的HTTP服務器和一個簡單的HTTP客戶端。http.Server是一個基于事件的HTTP服務器;http.request則是一個HTTP客戶端工具,用于向HTTP服務器發送請求,實現內容抓取。
一. HTTP服務器
http.Server提供一套封裝級別很低的API,僅僅是流控制和簡單的消息解析。
可以使用http.CreateServer()來創建一個http.Server實例。
var http = require('http');http.createServer(function (request, response){ response.writeHead(200, {'Content-Type': 'text/html'}); response。write("Server start!"); response.end('Hello World/n');}).listen(8080, "127.0.0.1");console.log('Server running on port 8080.');http.createServer創建了一個http.Server實例,將一個函數作為HTTP請求處理函數。這個函數接受兩個參數,分別是請求對象(req)和響應對象(res)。
二. http.ServerRequest
http.ServerRequest是HTTP請求信息。一般由http.Server的request事件發送,作為第一個參數傳遞。
HTTP請求一般分為兩部分:請求頭和請求體。
http.ServerRequest提供了以下3個事件用于控制請求體傳輸。
(1) data:當請求體數據到來時,該事件被觸發。該事件提供一個參數trunk,表示接收到的數據。如果該事件沒有被監聽,那么請求體將會被拋棄;
(2) end:當請求體數據傳輸完成時觸發;
(3) close:用戶當前請求結束時觸發。
ServerRequest的屬性

三. 獲取GET請求內容
http.ServerRequest提供的屬性沒有類似于PHP語言中的$_GET或$_POST的屬性,那我們該如何接受客戶端的表單請求呢?由于GET請求直接被嵌入在路徑中,因此可以手動解釋后面的內容作為GET請求的參數。
實例:
var http = require("http");var url = require("url");var util = require("util");http.createServer(function(req, res) { res.writeHead(200, {"Content-Type": "text/html"}); res.end(util.inspect(url.parse(req.url, true)));}).listen(3000);在瀏覽器中訪問http://127.0.0.1:3000/?name=deng&age=22,返回結果如下:
Url { protocol: null, slashes: null, auth: null, host: null, port: null, hostname: null, hash: null, search: '?name=deng&age=22', query: { name: 'deng', age: '22' }, pathname: '/', path: '/?name=deng&age=22', href: '/?name=deng&age=22' }通過url.parse,原始的path被解釋為一個對象,其中query就是請求的內容。
四. 獲取POST請求內容
POST請求的全部內容都在請求體中。
五. http.ServerReponse
http.ServerReponse是返回給客戶端的信息,決定了用戶最終能看到的結果,一般作為http.createServer(function(req, res) {})函數中的res參數傳遞。
http.ServerReponse有三個重要的成員函數,用于返回響應頭、響應內容以及結束請求。
response.writeHead(statusCode, [headers]) :向請求的客戶端發送響應頭。statusCode是HTTP狀態碼,headers是一個表示響應頭屬性的對象;
response.write(data, [encoding]) :向請求的客戶端發送相應內容。data表示要發送的內容,encoding表示編碼方式(默認是utf-8);
response.end([data], [encoding]) :結束響應,告知客戶端所有發送已經完成。當所有要返回的內容發送完畢的時候,該函數必須被調用一次。如果不調用該函數,客戶端將永遠處于等待狀態。
六. HTTP客戶端
http模塊提供了兩個函數http.request和http.get,作為客戶端想HTTP服務器發起請求。
1. http.request()
http.request(options, callback)發起HTTP請求。
其中options的常用參數如下:
host:請求網站的域名或IP地址;
port:請求網站的端口,默認是80;
method:請求方法,默認是GET;
path:請求的相對于根的路徑,默認是”/”;
headers:請求頭的內容;
var http = require("http");var querystring = require("querystring");var contents = querystring.stringify({ name: "deng", age: 22});var options = { host: "dengzhr.com", method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", "Content-Length": contents.length }};var req = http.request(options, function(res) { res.setEncoding("utf8"); res.on("data", function(data) { console.log(data); });});req.write(contents);req.end();在發送POST請求時,一定不要忘記通過req.end()結束請求,否則服務器將不會收到消息。
2. http.get()
http.get(options, callback)是http模塊的用于處理GET請求的更加簡便的方法。不需要手動調用req.end() 。
實例:
var http = require("http");http.get({host: "dengzhr.com"}, function(res) { res.setEncoding("utf8"); res.on("data", function(data) { console.log(data); });});總結
以上就是這篇文章的全部內容了,希望能對大家的學習或者工作帶來一定的幫助,如果有疑問大家可以留言交流。
新聞熱點
疑難解答