使用 Node 創(chuàng)建 Web 服務(wù)器
var http = require('http');
var fs = require('fs');
var url = require('url');
// 創(chuàng)建服務(wù)器
http.createServer( function (request, response) {
// 解析請求努溃,包括文件名
var pathname = url.parse(request.url).pathname;
// 輸出請求的文件名
console.log("Request for " + pathname + " received.");
// 從文件系統(tǒ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/plain
response.writeHead(404, {'Content-Type': 'text/html'});
}else{
// HTTP 狀態(tài)碼: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/html'});
// 響應(yīng)文件內(nèi)容
response.write(data.toString());
}
// 發(fā)送響應(yīng)數(shù)據(jù)
response.end();
});
}).listen(8081);
// 控制臺會輸出以下信息
console.log('Server running at http://127.0.0.1:8081/');
接下來我們在該目錄下創(chuàng)建一個 index.htm 文件础淤,代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>厲害了霹购,我的國</h1>
</body>
</html>
image.png
使用 Node 創(chuàng)建 Web 客戶端
var http = require('http');
// 用于請求的選項
var options = {
host: 'localhost',
port: '8081',
path: '/index.htm'
};
// 處理響應(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ā)送請求
var req = http.request(options, callback);
req.end();
image.png