Node.js 提供了 http 模塊,http 模塊主要用于搭建 HTTP 服務(wù)端和客戶端,使用 HTTP 服務(wù)器或客戶端功能必須調(diào)用 http 模塊,代碼如下:
var http = require('http');
以下是演示一個(gè)最基本的 HTTP 服務(wù)器架構(gòu)(使用 8080 端口),創(chuàng)建 server.js 文件,代碼如下所示:
var http = require('http');
var fs = require('fs');
var url = require('url');
// 創(chuàng)建服務(wù)器
http.createServer( function (request, response) {
// 解析請(qǐng)求,包括文件名
var pathname = url.parse(request.url).pathname;
// 輸出請(qǐng)求的文件名
console.log("Request for " + pathname + " received.");
// 從文件系統(tǒng)中讀取請(qǐng)求的文件內(nèi)容
fs.readFile(pathname.substr(1), function (err, data) {
if (err) {
console.log(err);
// HTTP 狀態(tài)碼: 404 : NOT FOUND
// Content Type: text/html
response.writeHead(404, {'Content-Type': 'text/html'});
}else{
// HTTP 狀態(tài)碼: 200 : OK
// Content Type: text/html
response.writeHead(200, {'Content-Type': 'text/html'});
// 響應(yīng)文件內(nèi)容
response.write(data.toString());
}
// 發(fā)送響應(yīng)數(shù)據(jù)
response.end();
});
}).listen(8080);
// 控制臺(tái)會(huì)輸出以下信息
console.log('Server running at http://127.0.0.1:8080/');
接下來我們?cè)谠撃夸浵聞?chuàng)建一個(gè) index.html 文件,代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>新手站長(zhǎng)(xinshouzhanzhang.com)</title>
</head>
<body>
<h1>我的第一個(gè)標(biāo)題</h1>
<p>我的第一個(gè)段落。</p>
</body>
</html>
執(zhí)行 server.js 文件:
$ node server.js
Server running at http://127.0.0.1:8080/
接著我們?cè)跒g覽器中打開地址:http://127.0.0.1:8080/index.html,顯示如下圖所示:
執(zhí)行 server.js 的控制臺(tái)輸出信息如下:
Server running at http://127.0.0.1:8080/
Request for /index.html received. # 客戶端請(qǐng)求信息
使用 Node 創(chuàng)建 Web 客戶端
Node 創(chuàng)建 Web 客戶端需要引入 http 模塊,創(chuàng)建 client.js 文件,代碼如下所示:
var http = require('http');
// 用于請(qǐng)求的選項(xiàng)
var options = {
host: 'localhost',
port: '8080',
path: '/index.html'
};
// 處理響應(yīng)的回調(diào)函數(shù)
var callback = function(response){
// 不斷更新數(shù)據(jù)
var body = '';
response.on('data', function(data) {
body += data;
});
response.on('end', function() {
// 數(shù)據(jù)接收完成
console.log(body);
});
}
// 向服務(wù)端發(fā)送請(qǐng)求
var req = http.request(options, callback);
req.end();
新開一個(gè)終端,執(zhí)行 client.js 文件,輸出結(jié)果如下:文章來源:http://www.zghlxwxcb.cn/news/detail-818203.html
$ node client.js
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>新手站長(zhǎng)(xinshouzhanzhang.com)</title>
</head>
<body>
<h1>我的第一個(gè)標(biāo)題</h1>
<p>我的第一個(gè)段落。</p>
</body>
</html>
執(zhí)行 server.js 的控制臺(tái)輸出信息如下:文章來源地址http://www.zghlxwxcb.cn/news/detail-818203.html
Server running at http://127.0.0.1:8080/
Request for /index.html received. # 客戶端請(qǐng)求信息
到了這里,關(guān)于使用 Node 創(chuàng)建 Web 服務(wù)器的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!