{%hackmd /au2gfdvHR0mEjvR_NzROqA?both %} ###### tags: `Node.js` [Node.js] 用 Node.js 開啟伺服器 === [TOC] >  > <small>使用 Node.js 開啟一個後端伺服器</small> <h2 class="title">簡介</h2> - 會客製化 response 訊息到瀏覽器上去做瀏覽 <h2 class="title">如何使用</h2> - 先編輯好要使用的JS檔 - 使用終端機開啟該JS所在資料夾,輸入`node xxx.js`,就會啟動 - 想退出就使用`ctrl+c`,連按多次 >  > <small>在 Command line 輸入 node 可以使用 node.js 模組</small> <h2 class="title">程式碼解析</h2> - 首先載入 Node.js 中的 http 模組 - 使用這個模組可以開啟伺服器 ```javascript= // 載入 http 模組 const http = require("http") ``` - 開啟伺服器 - 使用 port:3000 進行連結 ```javascript= // 開啟伺服器。收到請求的時候,裡面的函式就會執行 http.createServer({ ... }) // 在 3000 port 開啟 .listen(process.env.PORT || 3000) ``` - 在`createServer`中加入`function(request, response){}` - 當有使用者或瀏覽器發出網路請求時,才會執行這段函式 - `request`:當有使用者來到這個網址,`request`就會產生資料出來, - 會獲得使用者的所有資料(使用甚麼瀏覽器、用哪個網址造訪.....) - 執行完就會把資料放在`request`上,會是一個物件 - `response`:代表回傳的訊息 ```javascript= http.createServer( function(request, response){ // 收到的 request 是一個物件 console.log(request) // url 的 "/" 是首頁的意思 if(request.url === "/"){ console.log("Receive request") // .writeHead 為 header 資訊 // 200 是狀態碼 // "text/HTML" 表示回傳的是 HTML 資料格式 // 如果希望顯示純文字,用 "text/plain" response.writeHead(200, {"Content-Type": "text/HTML"}) // .write 要顯示在網頁的內容 response.write("<h1>Index</h1>") response.end() } else { console.log("Receive request") response.writeHead(200, {"Content-Type": "text/HTML"}) response.write("<h1>Not Index</h1>") response.end() } } ) ``` >  > <small>`host`:用哪個網址造訪、`user-agent`:使用哪個瀏覽器</small> >  > <small>使用 GET</small> >  > <small>JS程式碼對應Network中的欄位</small> <h2 class="title">程式碼</h2> ```javascript= const http = require("http") http.createServer(function(request, response){ console.log(request) if(request.url === "/"){ console.log("Receive request") response.writeHead(200, {"Content-Type": "text/HTML"}) response.write("<h1>Index</h1>") response.end() } else { console.log("Receive request") response.writeHead(200, {"Content-Type": "text/HTML"}) response.write("<h1>Not Index</h1>") response.end() } }).listen(process.env.PORT || 3000) console.log("Server port: 3000") ```
×
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