-
Notifications
You must be signed in to change notification settings - Fork 104
Expand file tree
/
Copy pathserver.js
More file actions
42 lines (38 loc) · 962 Bytes
/
server.js
File metadata and controls
42 lines (38 loc) · 962 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
const http = require('http')
const { URL } = require('url')
const port = 8080
const server = http.createServer((req, res) => {
const { pathname } = new URL(req.url)
// api开头的是API请求
if (pathname.startsWith('/api')) {
// 再判断路由
if (pathname === '/api/users') {
// 获取HTTP动词
const method = req.method
if (method === 'GET') {
// 写一个假数据
const resData = [
{
id: 1,
name: '小明',
age: 18,
},
{
id: 2,
name: '小红',
age: 19,
},
]
res.setHeader('Content-Type', 'application/json')
res.end(JSON.stringify(resData))
return
}
}
}
res.statusCode = 200
res.setHeader('Content-Type', 'text/plain')
res.end('Hello World')
})
server.listen(port, () => {
console.log(`Server is running on http://127.0.0.1:${port}/`)
})