温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-08-25 10:40:34 来源:脚本之家 阅读:131 作者:_Artisan 栏目:web开发

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数据的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对亿速云网站的支持!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI