源代码在这里

Part 1. HelloWorld

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const http = require("http")
const host = process.env.HOST || "localhost"
const port = process.env.PORT || 3000

/**
* 用于处理请求的函数
*/
const requestHandler = (req, res) => {
res.statusCode = 200
res.setHeader("Content-Type", "text/plain")
res.end("Hello World")
}

// 创建 server
const server = http.createServer(requestHandler)

// 开启监听
server.listen(port, host, (err) => {
if (err) {
return console.log("something bad happened", err)
}

console.log(`server is listening on ${host}:${port}`)
})

Part 2. ContentType: JSON

1
2
3
4
5
const requestHandler = (req, res) => {
res.statusCode = 200
res.setHeader("Content-Type", "application/json")
res.end(JSON.stringify({ message: "Hello World" }))
}

JSON 返回意味着有一个 Content-Type Header 和对应的 JSON 文本 body

Part 3. Router

1
2
3
4
5
6
7
8
9
10
11
12
13
const requestHandler = (req, res) => {
res.statusCode = 200
switch (req.url) {
case "/json": {
jsonHandler(req, res)
break
}
default: {
defaultHandler(req, res)
break
}
}
}

可以通过 req.url 判定来源 url 以此提供路由功能