http.js
// 导入node内置的http模块
// 定义一个变量来接收这个模块
const http = require('http')
// 设置端口号port
const port = 3004
// 调用http模块的createServe方法
// require参数:表示浏览器向服务器请求的内容
// response参数:表示服务器向浏览器响应的内容
const serve = http.createServer((require,response) => {
console.log('来请求了,请求方式是:' + require.method);
console.log('来请求了,请求路径是:' + require.url);
// 设置响应状态码为200
response.statusCode = 200
// 设置响应头
response.setHeader('Content-Type', 'text/plain;charset=UTF-8')
// 设置响应体:真正返回给浏览器的内容
// response.end('hello world')
if (require.method === "GET") {
if(require.url === '/index.html') {
response.end('我是html页面')
} else if (require.url === '/joke') {
response.end('我是一个笑话')
} else {
response.end('我是主页面')
}
} else if (require.method === 'POST'){
// POST请求对应的不同情况
}
})
// 开启服务器
serve.listen(port,()=>{
})
狗狗接口
// 导入fs模块
const fs = require('fs')
// 导入path模块
const path = require('path')
// 声明一个变量 接收处理好的路径
const jsonPath = path.join(__dirname,'../data/dogs.json')
// 封装添加狗狗的方法
function addDog(dog,callback) {
// function addDog(dog,callback){
// 先读取原本的内容
fs.readFile(jsonPath, (err, data) => {
// 读取成功
if (!err) {
// 定义一个数组接收读取到的元素
const arr = JSON.parse(data)
// 向数组中增加元素
arr.push(dog)
// 向JSON文件写入数组元素
// 在向服务器发送数据时一般是字符串。
// 我们可以使用 JSON.stringify() 方法将JavaScript值轉化為JSON字符串。
fs.writeFile(jsonPath, JSON.stringify(arr), err => {
if (!err) {
console.log('写入成功')
if( callback instanceof Function) {
callback()
}
} else {
console.log('写入失败')
}
})
} else {
// 读取失败
console.log('读取失败')
}
})
}
// 封装的读取狗狗的方法
// function readDog () {
function readDog (callback) {
// 读取
fs.readFile(jsonPath,(err,data) => {
// 如果没错就打印数组
if(!err){
// console.log( JSON.parse(data) );
callback(JSON.parse(data));
}else {
// 打印错误
console.log(err);
}
})
}
// addDog('比熊')
// 模块内容暴露
module.exports = {
readDog,
addDog
}
const http = require('http')
// 导入狗狗模块
const dog = require('./module/dog')
const serve = http.createServer( (req,res) => {
res.statusCode = 200
res.setHeader('Content-Type','text/plain;charset=UTF-8')
// res.end('hello world')
if (req.url == '/randomDog' && req.method == 'GET'){
// res.end('我要返回一条狗狗')
dog.readDog((data) => {
// res.end('我要返回一条狗狗')
// res.end(data)
// res.end(JSON.stringify(data))
// 产生一个随机下标
const idx = Math.floor( Math.random() * data.length )
// 根据下标取出狗狗返回即可
res.end(data[idx])
})
} else {
// 如果不是get请求且访问的不是这个路径,统一返回hello world
res.end('hello world')
}
})
serve.listen(8844,() => {
console.log(`运行成功:端口号为:3001`);
})