天天看點

vue-cli中模拟資料的兩種方法

我所使用的是新版vue-cli

首先進行所需插件的安裝,vue-resource,json-server,proxyTable.

目錄結構如圖

在main.js中引入vue-resource子產品,Vue.use(vueResource).

1.使用json-server(不能用post請求)

接下來找到build目錄下的webpack.dev.conf.js檔案,在const portfinder = require('portfinder')後面引入json-server.

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

現在重新開機伺服器後浏覽器位址欄輸入localhost:3000能進入如下頁面則說明json server啟動成功了

現在找到config檔案夾下的index.js檔案,在dev配置中找到proxyTable:{} 并在其中配置

'/api':{
    changeOrigin:true, //示範允許跨域
    target:"http://localhost:3000", //接口的域名
    pathRewrite:{
        '^/api':'' //後面使用重寫的新路徑,一般不做更改
    }
}
複制代碼           

現在可以使用localhost:8080/api/apiName 請求json資料了

在項目中通過resource插件進行ajax請求

在data (){}前使用鈎子函數created:function(){
    this.$http.get('/api/newsList')
        .then(function(res){
            this.newsList = res.data //指派給data中的newsList
        },function(err){
            console.log(err)
        })
}
複制代碼           

2.使用express(可以使用post請求)

在項目中建立routes檔案并在其中建立api.js,内容如下:

const express = require('express')
const router = express.Router()
const apiData = require('../db.json')

router.post('/:name',(req,res)=>{
    if(apiData[req.params.name]){
        res.json({
            'error':'0',
            data:apiData[req.params.name]
        })
    }else{
        res.send('no such a name')
    }
})
複制代碼           

接下來找到build目錄下的webpack.dev.conf.js檔案,在const portfinder = require('portfinder')後面引入express,如下:

const express = require('express')
 const app = express()
 const api = require('../routes/api.js')
 app.use('/api',api)
 app.listen(3000)
複制代碼           
'/api':{
    changeOrigin:true, //示範允許跨域
    target:"http://localhost:3000", //接口的域名
    pathRewrite:{
        '^/api':'/api' //後面使用重寫的新路徑,一般不做更改
    }
}
複制代碼           

重新開機之後,便可以post請求通路資料了.

原文釋出時間為:2018年06月29日

作者:學前端的小新

本文來源:

掘金

 如需轉載請聯系原作者