建立Node.js 伺服器


Posted by mijouhsieh on 2021-12-24

  1. 因為 server間的溝通語言是http (hypertext transfer protocol)?
    所以,要載入http模組(因為常用所以Node.js內建有)。
    使用require方法
    const http = require('http')
    記得模組http小寫!

  2. 設定server相關變數
    主機名稱: 慣例本地主機會稱localhost
    通訊埠號
    const hostname = 'localhost'
    const port = 3000

3.建立主機
使用http模組內的方法 serverCreate,帶有一個函式,函式有2個參數。
req 請求、res 回應
res.statusCode 告訴client-side的請求是成功的(200),server會給予對應的資料。
res.setHeader 回應的資料其內容類別,使用text文字用html格式解析。
res.end 回應的內容,會呈現在瀏覽器上。
const server = http.serverCreate((req, res) => { res.statusCode = 200 res.setHeader = ('Content-Type', 'text/html') res.end(this sentence will show on browser) })

  1. 以監聽listen請求來啟動server,帶入3個參數,最後一個是匿名函式,console.log呈現在terminal裡。terminal輸入 node js檔名 ,以node執行js檔案。

    server.listen(port, hostname, ()=> { console.log(this will show on terminal Now is listening http://${hostname}:${port}`
    )}`

  1. 打開瀏覽器輸入 localhost:3000 即可見在JS檔中設定的內容。

注意: 若js有修改,儲存檔案後,瀏覽器並不會直接更新,需從terminal 指令ctrl+c 離開node環境,再重新用node js檔名 執行js檔,browser才會更新。

所以網頁開發不會以node.js寫網頁,會以express框架,express必須在Node.js環境下才可使用。


#Node.js server







Related Posts

3. ECMAScript - Notational Conventions 符號約定

3. ECMAScript - Notational Conventions 符號約定

CSS 定位 置中

CSS 定位 置中

CSS 衍生的資安問題(中) - 不用 Hot Update 也行

CSS 衍生的資安問題(中) - 不用 Hot Update 也行


Comments