node_前后端数据请求

目录结构

|___router
| |__index.js
| |__newsdata.json
| |__routerMethods.js
|
|___src
| |__index.html
| |__index.js
|
|___index.js

1.入口index.js

let http = require('http')
let service = require('./service/index.js')

// 1.执行router/index.js导入路由对象
let router = require('./router/index.js')
// 2.使用use方法配置路由
router.use('/getdata', router.getdata)

let server = http.createServer((req, res) => {
  // 3.发送请求
  router(req, res)

}).listen(8888)

2.router/index.js

let url = require('url')
let querystring = require('querystring')
let request = require('request')
let fs = require('fs')
// 导出路由方法,与路由设计分离
let routerMethods = require('./routerMethods.js')
//3.1设计路由理念
module.exports = (req, res) => {
  let urlObj = url.parse(req.url)
  let querystringObj = querystring.parse(urlObj.query)
  let methods = module.exports[urlObj.pathname.substr(1)]
  req.querystringObj = querystringObj
  if (methods) methods(req, res)
  else {
    //静态路由资源托管
    fs.readFile(__dirname + '/../src' + urlObj.pathname, (err, data) => {
      res.end(data)
    })
  }
}
//es6语法 对象合并
//2.2设计实现的分离
Object.assign(module.exports, routerMethods)
//2.1路由配置
module.exports.use = (url, callback) => {
  let urlProp = url.substr(1)
  module.exports[urlProp] = callback
}

3.router/routerMethods.js

//实现路由方法
let fs = require('fs')

let start = 5
module.exports = {
  getdata (req, res) {
    let count = req.querystringObj.count
    fs.readFile(__dirname + '/newsdata.json', (err, data) => {
      data = JSON.parse(data)
      if(count && count != 5) {
        let end = (Number(count)+start)
        res.end(JSON.stringify(data.slice(start, end)))
        start += 2
      }else res.end(JSON.stringify(data.slice(0, 5)))
    })
  }
}

4.newsdata.json

[{
  "id": "0001",
  "img": "https://p3.pstatp.com/list/190x124/pgc-image/6278c4e87c7445ecadc687714e589711",
  "title": "我国全面取消县级供电企业“代管”体制",
  "detail": "时政   中国电力报 ⋅  382评论 ⋅  33分钟前"
},{
  "id": "0002",
  "img": "https://p3.pstatp.com/list/190x124/pgc-image/RsKTsENA98VCW4",
  "title": "向美帝摇尾乞怜的教书害人匠",
  "detail": "传媒   环球网 ⋅  20评论 ⋅  40分钟前"
},{
  "id": "0003",
  "img": "https://p1.pstatp.com/list/190x124/pgc-image/RsA9sUaCBjDIlv",
  "title": "杭州初三男孩每天傍晚就“发疯”!妈妈吓得只能躲单位:网课成了一家三口的恶梦",
  "detail": "社会   中国青年网 ⋅  456评论 ⋅  49分钟前"
},{
  "id": "0004",
  "img": "https://p1.pstatp.com/list/190x124/pgc-image/24d23182556449f38634d2000abc4340",
  "title": "轮到意大利人被别国侮辱了",
  "detail": "国际   环球时报 ⋅  1684评论 ⋅  57分钟前"
},{
  "id": "0005",
  "img": "https://p9.pstatp.com/list/190x124/pgc-image/39ac6fcc7efb4f2787bba47fdfc92fd3",
  "title": "分手后才知道,他每天往返四个小时,只为了见我一面",
  "detail": "故事   三联生活周刊 ⋅  224评论 ⋅  1小时前"
},{
  "id": "0006",
  "img": "https://p9.pstatp.com/list/190x124/pgc-image/RsFxNEQ3reP1EU",
  "title": "雷神山的墙,火了",
  "detail": "社会   中国青年网 ⋅  7178评论 ⋅  1小时前"
},{
  "id": "0007",
  "img": "https://p3.pstatp.com/list/190x124/pgc-image/2c1ad4cd170746399d8f522e972ad0ce",
  "title": "胡锡进:就最近中国人的遭遇,说一下中俄关系的实际面貌",
  "detail": "国际   环球时报 ⋅  272评论 ⋅  1小时前"
},{
  "id": "0008",
  "img": "https://p1.pstatp.com/list/190x124/pgc-image/RrPOLxP9rVxgsc",
  "title": "卫星扫过中国的一片沙漠 外国专家都惊讶了",
  "detail": "科学   环球网 ⋅  332评论 ⋅  1小时前"
},{
  "id": "0009",
  "img": "https://p1.pstatp.com/list/190x124/pgc-image/RsM9OKXIW9qlr7",
  "title": "36岁新冠患者出院后死亡,王广发:是否复发不宜过早下结论",
  "detail": "健康   新京报 ⋅  498评论 ⋅  1小时前"
},{
  "id": "0010",
  "img": "https://p1.pstatp.com/list/190x124/pgc-image/RrqzoRW2Woiyc2",
  "title": "因疫被困男友家,我和未来婆婆都快处成姐妹了",
  "detail": "故事   新华网客户端 ⋅  1331评论 ⋅  1小时前"
},{
  "id": "0011",
  "img": "https://p1.pstatp.com/list/190x124/pgc-image/R6cefahHX9doHC",
  "title": "女人对你有了好感,相处时才会有的肢体语言,别傻傻不懂",
  "detail": "情感   光明网 ⋅  7评论 ⋅  2小时前"
},{
  "id": "0012",
  "img": "https://p9.pstatp.com/list/190x124/pgc-image/bf35da78f8334e6c8fd49f2d8327929c",
  "title": "魔幻纠纷!“价格屠夫”为3.38亿手撕京东,这场“互刚”大戏如何收场?",
  "detail": "科技   环球人物杂志 ⋅  193评论 ⋅  2小时前"
},{
  "id": "0013",
  "img": "https://p1.pstatp.com/list/190x124/pgc-image/RsJlLTNGJpHoc2",
  "title": "蟹肉棒是什么,你应该吃么?",
  "detail": "美食   中国经济网 ⋅  10评论 ⋅  2小时前"
},{
  "id": "0014",
  "img": "https://p1.pstatp.com/list/190x124/pgc-image/R6gvn63BhYjmsE",
  "title": "自热火锅安全吗?消防实验告诉你",
  "detail": "社会   光明网 ⋅  7评论 ⋅  2小时前"
},{
  "id": "0015",
  "img": "https://p3.pstatp.com/list/190x124/pgc-image/12800b57142d4d62b3716cbeac28f43a",
  "title": "挪威军队男女混住宿舍内部曝光 男女士兵一起叠被",
  "detail": "军事   环球时报 ⋅  2033评论 ⋅  2小时前"
},{
  "id": "0016",
  "img": "https://p3.pstatp.com/list/190x124/pgc-image/bdb2ee48eefa4cfc97ea873a2faf886b",
  "title": "他曾是“台独”铁杆支持者,如今在“绿地”台南升起了五星红旗",
  "detail": "时政   人民政协网 ⋅  209评论 ⋅  2小时前"
},{
  "id": "0017",
  "img": "https://p1.pstatp.com/list/190x124/pgc-image/Rqw40HXFGgGYUy",
  "title": "中国古籍中100句经典语录",
  "detail": "  光明网 ⋅  216评论 ⋅  2小时前"
},{
  "id": "0018",
  "img": "https://p3.pstatp.com/list/190x124/pgc-image/Rrgh96rCzFdkJ3",
  "title": "权威发布|新冠肺炎出院患者康复方案来了",
  "detail": "健康   健康报 ⋅  评论 ⋅  2小时前"
},{
  "id": "0019",
  "img": "https://p3.pstatp.com/list/190x124/pgc-image/RrsrYQtD4ZRhH9",
  "title": "@所有中小微企业:国家扶持来了,都是真金白银",
  "detail": "财经   人民网 ⋅  2745评论 ⋅  2小时前"
},{
  "id": "0020",
  "img": "https://p1.pstatp.com/list/190x124/pgc-image/RmqmgpaAQqiQK8",
  "title": "男生微信问你:“在干嘛”,高情商的女生都是这么回答的",
  "detail": "情感   光明网 ⋅  14评论 ⋅  3小时前"
}]

5.src/index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
  <script type="text/javascript" src="index.js"></script>
</head>
<body>
  <h1>今日头条</h1>
  <div id="app" class="container"></div>
</body>
  <script type="text/javascript">
  window.onload = () => {
    myRequest("get", 'http://localhost:8888/getdata?count=5', handleUpdata)
    window.onscroll = (ev) => {
      let scrollTop = document.documentElement.scrollTop
      let scrollHeight = document.documentElement.scrollHeight
      let windowHeight = document.documentElement.clientHeight;
      console.log(scrollTop)
      if (scrollTop + windowHeight == scrollHeight) myRequest("get", 'http://localhost:8888/getdata?count=2', handleUpdata)
    }
  }
  function handleUpdata(data) {
    for (let i = 0; i < data.length; i++) {
      app.innerHTML += `
        <div class="row">
          <div class="col-xs-4 col-md-3">
            <a href="javascript:;" class="thumbnail">
              <img src="${data[i].img}">
            </a>
          </div>
          <div class="col-xs-8 col-md-9">
            <h2><a href="javascript:;">${data[i].title}</a></h2>
            <p><a href="javascript:;">${data[i].detail}</a></p>
          </div>
        </div>
      `
    }
  }
  </script>
</html>

6.src/index.js

function myRequest (method, url, cb) {
  let xhr = new XMLHttpRequest()
  xhr.open(method, url)
  xhr.send()
  xhr.onreadystatechange = () => {
    if(xhr.readyState == 4) {
      let status = xhr.status
      if(status >=200 && status < 300 || status == 304) {
        cb(JSON.parse(xhr.responseText))
      }
    }
  }
}

猜你喜欢

转载自www.cnblogs.com/JunLan/p/12424191.html