溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

vue2.5.2使用http請求獲取靜態(tài)json數(shù)據(jù)的實例代碼

發(fā)布時間:2020-08-25 10:40:34 來源:腳本之家 閱讀:146 作者:_Artisan 欄目:web開發(fā)

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

// 獲取靜態(tài)json數(shù)據(jù)
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廣告發(fā)布",
   "url": "http://hearstone.com"
  }
 ],
 "login": {
  "username": "yudongdong",
  "userId": 123123
 },
 "getPrice": {
  "amount": 678
 },
 "createOrder": {
  "orderId": "6djk979"
 },
 "getOrderList": {
  "list": [
   {
    "orderId": "ddj123",
    "product": "數(shù)據(jù)統(tǒng)計",
    "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": "廣告發(fā)布",
    "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);
   })
  }
 }

總結(jié)

以上所述是小編給大家介紹的vue2.5.2使用http請求獲取靜態(tài)json數(shù)據(jù)的實例代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對億速云網(wǎng)站的支持!

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI