使用http模塊創建Web服務器
Web服務器的功能:
接受HTTP請求(GET、POST、DELETE、PUT、PATCH)
處理HTTP請求(自己處理,或請求別的程序處理)
做出響應(返回頁面、文件、各類數據等)
常見的Web服務器架構:
Nginx、Apache:負責接受HTTP請求,確定誰來處理請求,并返回請求的結果
php-fpm / php模塊:處理分配給自己的請求,并將處理結果返回給分配者
常見請求種類:
請求文件:包括靜態文件(網頁、圖片、前端JavaScript文件、css文件...),及由程序處理得到的文件
完成特定的操作:如登錄、獲取特定數據等
Node.js的Web服務器:
不依賴其他特定的Web服務器軟件(如Apache、Nginx、IIS......)
Node.js代碼處理請求的邏輯
Node.js代碼負責Web服務器的各種“配置”
使用Express創建Web服務器
簡單的Express服務器
靜態文件服務
路由
中間件
簡單的Express服務器:
var express = require('express'); var app = express(); app.get('', function(req, res){ <span style="white-space:pre"> </span>res.end('hello/n'); <span style="white-space:pre"> </span>}); <span style="white-space:pre"> </span>app.listen(18001, function afterListen(){ <span style="white-space:pre"> </span>console.log('express running on http://localhost:18001'); <span style="white-space:pre"> </span>});
靜態文件范圍:
網頁、純文本、圖片、前端JavaScript代碼、CSS樣式表文件、媒體文件、字體文件
使用Express訪問靜態文件
<span style="white-space:pre"></span>app.use(express.static('./public'));
路由:
將不同的請求,分配給相應的處理函數
區分:路徑、請求方法
三種路由實現方法:
path:比較簡單
Router:比較適合同一個路由下的多個子路由
route:比較適合API
中間件
Connect:Node.js的中間件框架
分層處理
每層實現一個功能
創建TCP服務器
使用net模塊創建TCP服務器
使用telnet連接TCP服務器
使用net創建TCP客戶端
利用node.js搭建簡單web服務器JS代碼部分:
var http = require('http');var url = require('url');var path = require('path');var fs = require('fs');var dir, arg = process.argv[2] || ''; // 命令行第三個參數,用來接收目錄,可為空,相對當前server.js文件的目錄名稱// 比如使用命令 node server debug,意思就是debug文件夾與server.js文件同級// 且你想以debug文件夾啟動web服務 http.createServer(function (req, res) {var pathname = __dirname + url.parse(req.url).pathname;dir = dir ? dir : pathname; // 記住dir(目錄)pathname = dir ? pathname.replace(dir, dir + arg + '/') : pathname; // 替換文件靜態路徑if (path.extname(pathname) == "") {pathname += "/";}if (pathname.charAt(pathname.length - 1) == "/") {pathname += "index.html"; // 入口文件,此處默認index.html} fs.exists(pathname, function (exists) {if (exists) {switch (path.extname(pathname)) {case ".html":res.writeHead(200, {"Content-Type": "text/html"});break;case ".js":res.writeHead(200, {"Content-Type": "text/javascript"});break;case ".css":res.writeHead(200, {"Content-Type": "text/css"});break;case ".gif":res.writeHead(200, {"Content-Type": "image/gif"});break;case ".jpg":res.writeHead(200, {"Content-Type": "image/jpeg"});break;case ".png":res.writeHead(200, {"Content-Type": "image/png"});break;default:res.writeHead(200, {"Content-Type": "application/octet-stream"});} // res可以自己添加信息來簡單交互 比如可以修改點header信息 或者修改返回的資源數據fs.readFile(pathname, function (err, data) {res.end(data);});}else {res.writeHead(404, {"Content-Type": "text/html"});res.end("<h1>404 Not Found</h1>");}});}).listen(8085, "127.0.0.5"); // 服務器端口console.log("server running at http://127.0.0.5:8085/");
新聞熱點
疑難解答