Node createServer 起手式

新增一個專案名稱,並在專案內新增一個app.js,在app.js 加入以下程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// 載入 http 模組
var http = require(‘http’)
// 使用 http.createServer() 方法建立 Web 伺服器,回傳一個 Server 實例
var server = http.createServer()
// 註冊 request 請求事件監聽,當前端請求過來,此事件就會被觸發,並且執行 callback 函式
server.on(‘request’, function (request, response) {
//表頭:函式內用 response 中的 writeHead 寫入如果正確呼叫到這支程式的狀態與回傳的內容,狀態:200為成功呼叫到此程式,把 Content-type 的 text/plain=>字串, 如果要回傳是網頁元素則是把 Content-type 改為 text/html
response.writeHead(200, {
// "Content-type": "text/html",
//"Content-type": "text/plain",

});
//text/html
//response.write("<h1>hello node!</h1>");

response.write(‘Hello World!’)
//
response.end()
// 也可以簡化成 response.end(‘Hello World!’)
})
// 綁定 port通訊埠,啟動伺服器
server.listen(8000, function () {
console.log(‘伺服器已在 port 8000 運行 …’)
})

終端機執行 node app.js , 開啟 http://127.0.0.1:8000

三考