1.實驗目的
? ? 使用Node.js創建一個簡單的HTTP服務器。
2.實驗方法
? ? 使用http模塊創建一個簡單的HTTP服務器,能夠通過fs模塊讀取文本、圖片等文件并通過服務器發送給瀏覽器。
3.實驗環境
? ? windows10操作系統
? ? node.js v8.9.4版本
4.實驗步驟
? ? 4.1. HTTP服務器搭建
const http = require("http"); //導入http模塊
const server = new http.Server(); //創建http.Server對象
server.on("request", function(req, res) { //客戶端請求時觸發request事件
res.writeHead(200, { //向請求的客戶端發送響應頭
"content-type": "text/plain"
});
let data = "hello,world";
res.write(data); //向請求的客戶端發送內容
res.end(); //結束請求
});
server.listen(3000, function() { //監聽端口3000
console.log('HTTP服務器開啟成功');
});
? ? 4.2. 訪問HTML頁面
? ? ? ? ? 執行上述程序后,即可打開瀏覽器(http://localhost:3000/)查看發送的文件。
圖一 瀏覽器查看
? ? 4.3. 舉一反三
? ? ? ? ? 引入fs模塊后,只需要根據文件類型替換響應頭就能實現向瀏覽器發送不同類型文件。
const http = require("http");
const fs = require("fs"); //引入fs模塊
const server = new http.Server();
server.on("request", function(req, res) {
res.writeHead(200, {
"content-type": "image/jpg" //更換響應頭
});
let data = fs.readFileSync("./girl.jpg"); //選擇發送的文件
res.write(data);
res.end();
});
server.listen(3000, function() {
console.log('HTTP服務器開啟成功');
});
? ? ? ? ? 響應頭與文件類型對應關系見參考文獻。
圖二 girl.jpg
圖三 瀏覽器查看
5 .參考文獻
- http模塊:http://nodejs.cn/api/http.html
- 響應頭與文件類型對應關系:http://tool.oschina.net/commons