標籤:啟動 src else 服務 www 找不到 取數 擷取 pre
摘要
什麼是web伺服器?
web伺服器一般指網站伺服器,是指駐留於網際網路上某種類型電腦的程式,Web伺服器的準系統就是提供Web資訊瀏覽服務。它只需支援HTTP協議、HTML文檔格式及URL,與用戶端的網路瀏覽器配合。
大多數 網頁伺服器都支援服務端的語言(php、python、ruby,asp.net)等,並通過語言從資料庫擷取資料,將結果返回給用戶端瀏覽器。
目前最主流的三個Web伺服器是Apache、Nginx、IIS。
使用Node建立web伺服器
Node.js 提供了 http 模組,http 模組主要用於搭建 HTTP 服務端和用戶端。引入http模組
//引入http模組var http=require("http");建立web伺服器
建立server.js檔案,內容如下:
//引入http模組var http=require("http");//引入fs模組var fs=require("fs");//引入url模組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 response.writeHead(404,{"Content-Type":"text/html"}); }else{ response.writeHead(200,{"Content-Type":"text/html"}); //回應檔內容 response.write(data.toString()); }; response.end(); });}).listen(5544);console.log("Server running at http://127.0.0.1:5544");
啟動調試
因為在訪問/時,因為在伺服器上找不到該檔案而報錯,在瀏覽器響應的狀態代碼為404
web伺服器
瀏覽器
接下來,我們建立一個名稱為index.html的頁面,內容如下:
<html> <head> <title>My first page.</title> </head> <body> <h1>Hello my page world. </h1> </body></html>
啟動server,瀏覽http://127.0.0.1:5544/index.html
通過Node建立web用戶端
建立client.js,代碼如下:
var http=require("http");//用於請求的選項var options={ host:"127.0.0.1", port:‘5544‘, path:"/index.html"};//處理響應的回呼函數var callback=function(response){ var body=‘‘; response.on(‘data‘,function(data){ body+=data; });response.on(‘end‘,function(){//資料接收完成console.log(body);});
};//向伺服器發送請求var req=http.createClient(options,callback);req.end();
輸出
資料
http://www.runoob.com/nodejs/nodejs-web-module.html
[Node.js]web模組