Node.js可以提供你很多模組,今天來探索如何使用 Node.js 的 http
模組來架設一個簡單的伺服器。
本篇使用模組require 載入你所需要的模組。這次我們使用‘http’ 模組來創造一個簡單的server。

資料參考
Node.js – createServer 起手式 – iT 邦幫忙::一起幫忙解決難題,拯救 IT 人的一天 (ithome.com.tw)
1.創建你的第一個 Node.js 伺服器
我們先載入 http 模組,使用 http 模組內的 createServer
這個方法,
在 createServer 中給一個函式,並給兩個參數:
- req (request) – 當使用者呼叫資料時所發出的請求。
- res (response) – 回傳給使用者的資料。
帶入 createServer 參數
JavaScript
檔案: node apphttp.js
const http =require( 'http');
const server =http.createServer(function(req, res){
res.writeHead(200,{'Content-Type':'text/plain'});
res.end('Hello, world')
})
server.listen('3000', function(){
console.log('server start on 3000 port')
})
2.運行你的伺服器
Visual Studio 開啟一個Terminal,進入你的專案資料夾裏頭,執行你的 node apphttp.js

Edge瀏覽器內的操作
在網頁內部按滑鼠右鍵,點選>> 檢查。

3.觀看伺服器運作狀態
點選>> Network (連線)
localhost 點進去

4.觀看伺服器運作狀態
JavaScript
檔案: node apphttp.js
http.createServer(function(req, res) {
console.log(res); // 觀看丟回來的res
res.writeHead(200,{'Content-Type':'text/plain'});
res.write("<h1>hello nodeJS!</h1>");
res.end();
}).listen(3000); //port

觀看Visual Studio 內的Terminal 狀態

Edge瀏覽器內的狀態

