大多數 web 伺服器都支持服務端的腳本語言(php、python、ruby)等,並通過腳本語言從資料庫獲取數據,將結果返回給客戶端瀏覽器。 目前最主流的三個Web伺服器是Apache、Nginx、IIS。 使用node創建伺服器 Node.js 提供了 http 模塊,http 模塊主要用於搭建 ...
大多數 web 伺服器都支持服務端的腳本語言(php、python、ruby)等,並通過腳本語言從資料庫獲取數據,將結果返回給客戶端瀏覽器。
目前最主流的三個Web伺服器是Apache、Nginx、IIS。
使用node創建伺服器
Node.js 提供了 http 模塊,http 模塊主要用於搭建 HTTP 服務端和客戶端,使用 HTTP 伺服器或客戶端功能必須調用 http 模塊
演示一個最基本的 HTTP 伺服器架構(使用 8080 埠)
創建 main.js 文件
var http=require("http"); var fs=require("fs"); var url=require("url"); //創建伺服器 http.createServer(function(req,res){ //解析請求的文件名 var pathname=url.parse(req.url).pathname; //被請求的文件已收到請求 console.log("被請求的文件"+pathname+"已收到請求"); //讀取文件內容 //pathname.substr(1) 去掉. fs.readFile(pathname.substr(1),function(err,data){ if(err){ console.log(err); res.writeHead(404,{"Content-Type":"text/html"});// HTTP 狀態碼: 404 : NOT FOUND }else{ res.writeHead(200,{"Content-Type":"text/html"});// HTTP 狀態碼: 200 : OK res.write(data.toString()); } res.end(); }) }).listen(8080); console.log("Server running at http://127.0.0.1:8080/");
該目錄下創建一個 index.html 文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index</title> </head> <body> <h1>標題</h1> <p>段落</p> </body> </html>
在瀏覽器中打開地址:http://127.0.0.1:8080/index.html
使用node創建web客戶端
client.js
var http=require("http"); //用於請求的選項 var options={ host:"localhost", port:"8080", path:"/index.html" }; //處理響應的回調函數 var callback=function(res){ var body=""; res.on("data",function(data){ body+=data; }) res.on("end",function(){ console.log(body); }) } //向伺服器發送請求 var req=http.request(options,callback); req.end();
(我把前面伺服器文件main.js改為了server.js)
然後新開一個終端,運行client.js
再回來看第一個終端
成功~