vue模擬后端獲取數據——json-server與express


轉載自:

https://blog.csdn.net/weixin_39728230/article/details/80293892

https://blog.csdn.net/lxkll/article/details/84284429

最近在跟着做vue2.0以上版本的一個購物平台,在涉及到模擬后台數據交互的時候,視頻里講的是通過json-server和express,由於之前的配置都是在build/dev-server.js文件下,dev-server.js在vue2.0都沒有了,整合到了build/webpack.dev.conf.js文件里,通過綜合幾篇博文,最終問題得以解決。

一、模擬后台數據交互,vue中需要使用vue-resource這個組件,首先需要下載該組件:

     1. cnpm install vue-resource --save

     2. 在main.js文件中引入該組件並使用:

            import VueResource from 'vue-resource' 

            Vue.use( VueResource )

具體如下圖: 

3. 接下來就可以在任何組件內部使用了:

            this.$http.get( ).then( (res)  => {} , (err) => { })   (then前面獲取了一個promise對象)

上面步驟是用vue-resource來進行數據請求的大體流程,作為前端,我們只關注前端的開發,所以使用mock data來模擬后台傳數據,主要有兩種方式:

1)json-server模擬數據;此方法只能發送get請求不能發送post請求

2)express啟動數據服務;get請求和post請求都可以發送

二、 json-server

首先npm安裝

npm install json-server --save
然后在build/webpack.dev.conf.js中進行配置

將下面代碼片段加入到webpack.dev.conf.js中

/*----------------jsonServer---------*/
/*引入json-server*/
const jsonServer = require('json-server')
/*搭建一個server*/
const apiServer = jsonServer.create()
/*將db.json關聯到server*/
const apiRouter = jsonServer.router('db.json')
const middlewares = jsonServer.defaults()
apiServer.use(middlewares)
apiServer.use(apiRouter)
/*監聽端口*/
apiServer.listen(3000, () => {
  console.log('JSON Server is running')
})

  

配置完成以后,重新npm run dev 啟動,瀏覽器輸入localhost:3000,出現如下圖,說明配置成功

 

現在還有一個問題,我們代碼的服務端接口是8080,json-server的服務端端口是3000。端口不同,這樣請求會存在一個跨域問題,所以這里要做一個服務端代理的配置,配置config/index.js中找到proxyTable,並添加一下內容:

// 配置轉化:從3000 => 8080
    proxyTable: {
       '/api': {
             changeOrigin: true,// 如果接口跨域,需要進行這個參數配置
             target: 'http://localhost:3000',// 接口的域名
             pathRewrite: {
               '^/api': ''//后面可以使重寫的新路徑,一般不做更改
             }
         }
    },

  

注意:配置好后,一定要npm run dev 重新啟動項目

當在瀏覽器地址欄輸入:http://localhost:8080/api  就等同於http://localhost:3000端口了

4.要訪問並獲取數據,就需要有數據(假數據),這時候需要在vue文件夾的根目錄下創建一個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"
}
]
}

將db.json放在根目錄下(與index.html在同一目錄)

三、express

1. 找到webpack.dev.conf.js文件,

//express 配置server
  
var apiServer = express()  
var bodyParser = require('body-parser')  
apiServer.use(bodyParser.urlencoded({ extended: true }))  
apiServer.use(bodyParser.json())  
var apiRouter = express.Router()  
var 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(apiRouter);  
apiServer.listen(3000, function (err) {  
  if (err) {  
    console.log(err)  
    return  
  }  
  console.log('Listening at http://localhost:' + 3000 + '\n')  
})  

  2.同樣的, 在config/index.js文件下進行proxyTable的配置

proxyTable: {
      // 訪問/api/時,跳轉到3000端口
      '/api': {
        changeOrigin: true, // 如果接口跨域,需要進行這個參數配置
        target: 'http://localhost:3000',// 接口的域名
        pathRewrite: {
          '^/api': ''//后面可以使重寫的新路徑,一般不做更改
        }
      }
    },

 

  

最最最重要的是: build和config以及db.json文件中有任何修改,都必須重新 " npm run dev" 一次。另外,這兩種方法一旦"npm run dev" 以后,若是改動了以上的文件,必須關閉git bash窗口,重新打開進行 "npm run dev"

 




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM