# 一、npm install express --save
npm install nodemon -g
# 二、 写代码
const express = require('express')
// 创建服务器对象
const app = express()
// 定义端口
const port = 3000
// 引入文件模块
const fs = require('fs')
// 引入路径模块
const path = require('path')
// 注册路由
app.get('/info', (req, res) => {
// 打印浏览器地址栏中的请求参数
console.log("req.query", req.query);
const {
num
} = req.query
// 引用文件
const fullpath = path.join(__dirname, './data.json')
// 读取此文件的内容, 数据格式为 ["qqqqqqqq", "wwwwwwwwwww", "eeeeeeeeeeee", "rrrrrrrrrrrr", "ttttttttttt", "yyyyyyyyyyyy", "uuuuuuuuu"]
fs.readFile(fullpath, 'utf-8', (err, data) => {
if (!err) {
const jokes = JSON.parse(data)
// console.log('radom :>> ', jokes[radom]);
let joke_list = [], i = 0
while (i < num) {
const radom = Math.floor(Math.random() * jokes.length)
joke_list.push(jokes[radom])
i++
}
// 返回一个数组
res.send({
msg: 'success',
name: joke_list
})
}
})
})
// 开启服务器
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
})
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
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