大多數 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

再回來看第一個終端

成功~
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/142387.html
標籤:JavaScript
上一篇:NPM: 日常開發環境配置
下一篇:第二次JSP作業
