在很多場景中,我們的服務器都需要跟用戶的瀏覽器打交道,如表單提交。
表單提交到服務器一般都使用 GET/POST 請求。
本章節我們將為大家介紹 Node.js GET/POS T請求。
01、獲取GET請求內容
由于GET請求直接被嵌入在路徑中,URL是完整的請求路徑,包括了?后面的部分,因此你可以手動解析后面的內容作為GET請求的參數。
node.js 中 url 模塊中的 parse 函數提供了這個功能。
var http = require('http');
var url = require('url');
var util = require('util');
http.createServer(function(req, res){
res.writeHead(200, {'Content-Type': 'text/plain; charset=utf-8'});
res.end(util.inspect(url.parse(req.url, true)));
}).listen(3000);
02、獲取 URL 的參數
我們可以使用 url.parse 方法來解析 URL 中的參數,代碼如下:
var http = require('http');
var url = require('url');
var util = require('util');
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("網站 URL:" + params.url);
res.end();
}).listen(3000);
03、獲取 POST 請求內容
POST 請求的內容全部的都在請求體中,http.ServerRequest 并沒有一個屬性內容為請求體,原因是等待請求體傳輸可能是一件耗時的工作。
比如上傳文件,而很多時候我們可能并不需要理會請求體的內容,惡意的POST請求會大大消耗服務器的資源,所有node.js 默認是不會解析請求體的,當你需要的時候,需要手動來做。
var http = require('http');
var querystring = require('querystring');
http.createServer(function(req, res){
// 定義了一個post變量,用于暫存請求體的信息
var post = '';
// 通過req的data事件監聽函數,每當接受到請求體的數據,就累加到post變量中
req.on('data', function(chunk){
post += chunk;
});
// 在end事件觸發后,通過querystring.parse將post解析為真正的POST請求格式,然后向客戶端返回。
req.on('end', function(){
post = querystring.parse(post);
res.end(util.inspect(post));
});
}).listen(3000);
結果:
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>' +
'網站 URL: <input name="url"><br>' +
'<input type="submit">' +
'</form>' +
'</body></html>';
http.createServer(function (req, res) {
var body = "";
req.on('data', function (chunk) {
body += chunk;
});
req.on('end', function () {
// 解析參數
body = querystring.parse(body);
// 設置響應頭部信息及編碼
res.writeHead(200, {'Content-Type': 'text/html; charset=utf8'});
if(body.name && body.url) { // 輸出提交的數據
res.write("網站名:" + body.name);
res.write("<br>");
res.write("網站 URL:" + body.url);
} else { // 輸出表單
res.write(postHTML);
}
res.end();
});
}).listen(3000);
--------------------------------------------Node.js 工具模塊---------------------------------------
在 Node.js 模塊庫中有很多好用的模塊。接下來我們為大家介紹幾種常用模塊的使用:
序號
模塊名 & 描述
1
[**OS 模塊**](http://www.runoob.com/nodejs/nodejs-os-module.html)提供基本的系統操作函數。
2
[**Path 模塊**](http://www.runoob.com/nodejs/nodejs-path-module.html)提供了處理和轉換文件路的工具。
3
[**Net 模塊**](http://www.runoob.com/nodejs/nodejs-net-module.html)用于底層的網絡通信。提供了服務端和客戶端的的操作。
4
[**DNS 模塊**](http://www.runoob.com/nodejs/nodejs-dns-module.html)用于解析域名。
5
[**Domain 模塊**](http://www.runoob.com/nodejs/nodejs-domain-module.html)簡化異步代碼的異常處理,可以捕捉處理try catch無法捕捉的。
--------------------------------------------Node.js Web 模塊--------------------------------
01、什么是 Web 服務器?
Web服務器一般指網站服務器,是指駐留于因特網上某種類型計算機的程序,Web服務器的基本功能就是提供Web信息瀏覽服務。它只需支持HTTP協議、HTML文檔格式及URL,與客戶端的網絡瀏覽器配合。
大多數 web 服務器都支持服務端的腳本語言(php、python、ruby)等,并通過腳本語言從數據庫獲取數據,將結果返回給客戶端瀏覽器。
目前最主流的三個Web服務器是Apache、Nginx、IIS。
02、Web 應用架構
Client - 客戶端,一般指瀏覽器,瀏覽器可以通過 HTTP 協議向服務器請求數據。
Server - 服務端,一般指 Web 服務器,可以接收客戶端請求,并向客戶端發送響應數據。
Business - 業務層, 通過 Web 服務器處理應用程序,如與數據庫交互,邏輯運算,調用外部程序等。
Data - 數據層,一般由數據庫組成。
03、使用 Node 創建 Web 服務器
Node.js 提供了 http 模塊,http 模塊主要用于搭建 HTTP 服務端和客戶端,使用 HTTP 服務器或客戶端功能必須調用 http 模塊,代碼如下:
var http = require('http');
以下是演示一個最基本的 HTTP 服務器架構(使用8081端口),創建 server.js 文件,代碼如下所示:
var http = require('http');
var fs = require('fs');
var url = require('url');
// 創建服務器
http.createServer( function (request, response) {
// 解析請求,包括文件名
var pathname = url.parse(request.url).pathname;
// 輸出請求的文件名
console.log("Request for " + pathname + " received.");
// 從文件系統中讀取請求的文件內容
fs.readFile(pathname.substr(1), function (err, data) {
if (err) {
console.log(err);
// HTTP 狀態碼: 404 : NOT FOUND
// Content Type: text/plain
response.writeHead(404, {'Content-Type': 'text/html'});
}else{
// HTTP 狀態碼: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/html'});
// 響應文件內容
response.write(data.toString());
}
// 發送響應數據
response.end();
});
}).listen(8081);
// 控制臺會輸出以下信息
console.log('Server running at http://127.0.0.1:8081/');
接下來我們在該目錄下創建一個 index.htm 文件,代碼如下:
<html>
<head>
<title>Sample Page</title>
</head>
<body>
Hello World!
</body>
</html>
執行 server.js 文件:
$ node server.js
Server running at http://127.0.0.1:8081/
04、使用 Node 創建 Web 客戶端
Node 創建 Web 客戶端需要引入 http 模塊,創建 client.js 文件,代碼如下所示:
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();
05、使用 Node 創建 Web 客戶端
Node 創建 Web 客戶端需要引入 http 模塊,創建 client.js 文件,代碼如下所示
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();
新開一個終端,執行 client.js 文件,輸出結果如下:
$ node client.js
<html>
<head>
<title>Sample Page</title>
</head>
<body>
Hello World!
</body>
</html>
執行 server.js 的控制臺輸出信息如下:
Server running at http://127.0.0.1:8081/
Request for /index.htm received. # 客戶端請求信息