欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

vue2.5.2使用http请求获取静态json数据的实例代码

程序员文章站 2022-03-20 14:58:21
1.配置 build/webpack.dev.conf.js // 获取静态json数据 const express = require('express')...

1.配置 build/webpack.dev.conf.js

// 获取静态json数据
const express = require('express')
const app = express()
const apiserver = express()
const bodyparser = require('body-parser')
apiserver.use(bodyparser.urlencoded({ extended: true }))
apiserver.use(bodyparser.json())
const apirouter = express.router()
const fs = require('fs')
apirouter.route('/:apiname')
 .all(function (req, res) {
  fs.readfile('./db.json', 'utf8', function (err, data) {
   if (err) throw err
   var data = json.parse(data)
   if (data[req.params.apiname]) {
    res.json(data[req.params.apiname])
   }
   else {
    res.send('no such api name')
   }
  })
 })
apiserver.use('/api', apirouter);
apiserver.listen(8081, function (err) {
 if (err) {
  console.log(err)
  return
 }
 console.log('listening at http://localhost:' + (8081) + '\n')
})

2.新建 db.json

{
 "getnewslist": [
  {
   "id": 1,
   "title": "新闻条目1新闻条目1新闻条目1新闻条目1",
   "url": "http://starcraft.com"
  },
  {
   "id": 2,
   "title": "新闻条目2新闻条目2新闻条目2新闻条目2",
   "url": "http://warcraft.com"
  },
  {
   "id": 3,
   "title": "新闻条3新闻条3新闻条3",
   "url": "http://overwatch.com"
  },
  {
   "id": 4,
   "title": "新闻条4广告发布",
   "url": "http://hearstone.com"
  }
 ],
 "login": {
  "username": "yudongdong",
  "userid": 123123
 },
 "getprice": {
  "amount": 678
 },
 "createorder": {
  "orderid": "6djk979"
 },
 "getorderlist": {
  "list": [
   {
    "orderid": "ddj123",
    "product": "数据统计",
    "version": "高级版",
    "period": "1年",
    "buynum": 2,
    "date": "2016-10-10",
    "amount": "500元"
   },
   {
    "orderid": "yuj583",
    "product": "流量分析",
    "version": "户外版",
    "period": "3个月",
    "buynum": 1,
    "date": "2016-5-2",
    "amount": "2200元"
   },
   {
    "orderid": "pmd201",
    "product": "广告发布",
    "version": "商铺版",
    "period": "3年",
    "buynum": 12,
    "date": "2016-8-3",
    "amount": "7890元"
   }
  ]
 }
}

3.通过 localhost:8081/api/getnewslist 访问

4.在页面中获取的方式

export default {
  data() {
   newslist: []
  },
  created: function(){
   this.$http.get('api/getnewslist').then((res)=> {
    this.newslist = res.data
   },(err)=> {
    console.log(err);
   })
  }
 }

总结

以上所述是小编给大家介绍的vue2.5.2使用http请求获取静态json数据的实例代码,希望对大家有所帮助