六角體驗營 # Node.js 核心模組 : createServer ## 1. http 模組: node.js內建模組 > 透過 createServer 執行匿名function * #### STEP1. 載入內建模組 ```= var http = require('http'); ``` * #### STEP2. 開啟伺服器 ```= //1. 兩組引數傳遞數據 http.createServer(function(request,response){ //2. 200 OK 成功回傳 回傳資料格式為文字 response.writeHead(200,{"Content-Type":"text/plain"}); reponse.write('hello!!'); //回傳的資料 --------------------------- //資料格式若為html(以下) //response.writeHead(200,{"Content-Type":"text/html"}); //reponse.write('<h1>hello!!</h1>'); --------------------------- //3. 結束請求 reponse.end(); }).listen(8080); //4. 開啟一個監聽port ``` * #### STEP2. 檢查伺服器是否成功開啟 browser中使用localhost: 8080開啟  ## 2. http 模組: require / request / response ### 2-1. 觀察 request 引數是什麼資料 * response 回傳數據格式 Content-Type * text/plain : 文字格式 * text/html : html格式 ```= var http = require('http'); http.CreateServer(function(request,response){ -----------HERE-------------- console.log(request); //必須要在瀏覽器打開後,再回到node.js的 terminal觀察物件 ----------------------------- response.writeHead(200,{"Content-Type":"text/plain"}); response.write("hello!!"); response.end(); }).listen(8080); ``` * #### 使用 node.js的 terminal 觀察 **request物件** * 要打開瀏覽器 localhostL:port 才會成功開啟 server  * #### **request 物件資料 url** ```= var http = require('http'); http.CreateServer(function(request,response){ -----------HERE-------------- console.log(request.url); ----------------------------- response.writeHead(200,{"Content-Type":"text/plain"}); response.write("hello!!"); response.end(); }).listen(8080); ``` * 手動更新將url新增/hello  * terminal回傳url為 /hello (favicon為url前面的logo icon)  * #### 可在DevTools中觀察 network 傳遞資料 * Headers 可看到Content-Type * response 會看到回傳的資料  ## 3. port 通訊埠 * 本地伺服器: 模擬伺服器使用的 IP 127.0.0.1(即localhost) * 127.0.0.1:8080 等同 localhost:8080 * port 不可重複,常見用 8080 測試 * 幾個常用的port |port | 位置 | | -------- | -------- | | 21 | FTP | | 80 | http | | 3389 | 遠端桌面 |
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up