使用 Node.js 開啟第一個網頁伺服器

使用 Node.js 我們可以非常輕鬆建立起一個網頁伺服器,Node.js 為開發者提供一個核心模組 http,這個模組提供我們創建網頁伺服器的各種 API。

起手式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 載入模組
var http = require('http')

// 使用 http.createServer() 方法建立 Web 伺服器,回傳一個 Server 實例
var server = http.createServer()

// 註冊 request 請求事件監聽,當前端請求過來,此事件就會被觸發,並且執行 callback 函式
server.on('request', function () {
console.log('收到客戶端請求')
})

// 綁定 port,啟動伺服器
server.listen(8000, function () {
console.log('伺服器已在 port 8000 運行 ...')
})

運行伺服器,接著開啟瀏覽器輸入 127.0.0.1:8000 或是 localhost:8000,來試著造訪剛剛創建在本機的網頁伺服器

如果要停止伺服器服務,在 command line 中按 ctrl + C 即可終止。

處理請求事件

server.on() 監聽的 callback 可以接收兩個函數,分別為 requestresponse

取得請求路徑

1
2
3
server.on('request', function (request, response) {
console.log('客戶端請求路徑是' + request.url)
})

測試

回應數據到瀏覽器

透過 write() 方法回傳回應內容,並且透過 end() 告訴瀏覽器這次的請求已結束,請瀏覽器停止這次的響應。

1
2
3
4
5
server.on('request', function (request, response) {
response.write('Hello World!')
response.end()
// 也可以簡化成 response.end('Hello World!')
})

接著造訪 127.0.0.1:8000

依不同的請求路徑回應不同內容

到目前為止,任何的請求路徑都會回應相同的內容,例如:不管瀏覽器的 url 是 127.0.0.1:8000 或是 127.0.0.1:8000/login ..,伺服器目前都只會回應 你好世界!,要如何讓它去判斷請求呢? 其實若你已經會 JavaScript 的基本應用,這題非常的簡單。

我們可以利用剛剛用過的 request.url 搭配 if..else 來判斷不同請求,並回傳對應內容。

1
2
3
4
5
6
7
8
9
10
server.on('request', function (request, response) {
var url = request.url
if (url === '/') {
response.end('你好世界!')
} else if (url === '/login') {
response.end('Login page')
} else {
response.end('404 page not found!')
}
})

回應的內容只能是字串或是二進制數據(Buffer)

這邊直接破題了,我們直接來證實看看這個標題是不是正確的吧

1
2
3
server.on('request', function (request, response) {
response.end(12345)
})

這時試著開啟伺服器 node main.js,終端機直接跳出錯誤提示,導致無法正常開啟伺服器

1
TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be one of type string or Buffer. Received type number

它告訴我們,必須只能是 字串 或者 二進制數據,但是剛剛接收到的型別是數字。

那如果要回應一個物件或是陣列的話可以嗎?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
server.on('request', function (request, response) {
var family = [
{
name: 'Dylan',
age: 18
},
{
name: 'Paul',
age: 80
},
{
name: 'John',
age: 5
}
]
response.end(family)
})

果然又噴出了一樣的錯誤

1
TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be one of type string or Buffer. Received type object

既然只能允許字串(與二進制數據),還記得以前在寫 JavaScript 時是如何將物件轉成字串的嗎?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
server.on('request', function (request, response) {
var family = [
{
name: 'Dylan',
age: 18
},
{
name: 'Paul',
age: 80
},
{
name: 'John',
age: 5
}
]
response.end(JSON.stringify(family))
})