要求:
在server.js中写代码,提供一个名为getList的接口。具体要求如下:
-
方式:get
-
返回值:
-
(1)50%的可能成功返回:
-
{ data: '一句你想说的话', message:'请求成功' code: 200 }
-
(2)50%的可能成功返回:
-
{ data: '', message:'系统故障' code: 500 }
思路:
引入核心模块==>创建服务==>判断接口是否正确==>正确:读入数据并返回==>不正确:返回404
代码:
1.引入核心模块:http fs及path
const http = require('http')
const fs = require('fs')
const path = require('path')
2.创建服务
const server = http.createServer((req, res) => {
res.end('ok')
}
})
3.启动服务
server.listen(8015, () => {
console.log('8015,已就绪...');
})
4.判断接口及请求方式
if (req.url === '/someword' && req.method === 'GET') {
res.end('ok')
})
}else {
res.statusCode = 404
res.end('not found')
}
5.利用path.join()拼接绝对路径
const filePath = path.join(__dirname, 'data.json')
6.读入数据
fs.readFile(filePath, (err, data) => {
res.end('ok')
}
7.利用随机数,达到50%获取返回值的效果
fs.readFile(filePath, (err, data) => {
// 读取到的data是字符串,将其转换成数组形式
const arr = JSON.parse(data)
// 定义数组索引,0-1随机并取整
const index = Math.round(Math.random())
res.setHeader('content-type', 'application/json;charset=utf8')
//end发送只能是字符串或buffer,因此需要转换,并根据随机索引,达成50%获取返回值的效果
res.end(JSON.stringify(arr[index]))
})
8.完整代码
const http = require('http')
const fs = require('fs')
const path = require('path')
const server = http.createServer((req, res) => {
// console.log('当前的请求方式是:', req.method);
if (req.url === '/someword' && req.method === 'GET') {
// 读入数据并返回
const filePath = path.join(__dirname, 'data.json')
// console.log(filePath);
fs.readFile(filePath, (err, data) => {
// 读取到的data是字符串,将其转换成数组形式
const arr = JSON.parse(data)
// 定义数组索引,0-1随机并取整
const index = Math.round(Math.random())
res.setHeader('content-type', 'application/json;charset=utf8')
//end发送只能是字符串或buffer,因此需要转换,并根据随机索引,达成50%获取返回值的效果
res.end(JSON.stringify(arr[index]))
})
} else {
res.statusCode = 404
res.end('not found')
}
})
server.listen(8015, () => {
console.log('8015,已就绪...');
})