JSON-Server主要的作用是搭建一台JSON服務器,測試一些業務邏輯(我之前都是采用讀取文件的方式尷尬)。
一、安裝
npm install --save json-server
前提是已經安裝好了node環境,並且初始化好了項目。
二、提供json數據文件。
在項目根目錄下,新建一個 JSON 文件db.json。
三、配置json-server
在build\webpack.dev.conf.js下配置,如果是用舊版本的手腳架工具初始化的項目,是在build/dev-server.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 dev run 重啟項目,然后再地址欄輸入http://localhost:3000 就可以訪問到數據。
五、設置代理
最后做一下瀏覽器代理設置,在 config/index.js中:
/*代理配置表,在這里可以配置特定的請求代理到對應的API接口*/ /* 下面的例子將代理請求 /api/getNewsList 到 http://localhost:3000/getNewsList*/ proxyTable: { '/api': { changeOrigin: true,// 如果接口跨域,需要進行這個參數配置 target: 'http://localhost:3000',// 接口的域名 pathRewrite: { '^/api': ''//后面可以使重寫的新路徑,一般不做更改 } }
具體設置代理的方法,參見:Vue-接口跨域請求調試proxyTable
六、最后驗證一下代理是否成功
在瀏覽器輸入地址:http://localhost:8080/api。
七、使用
使用vue-resouce發送Ajax獲取數據。
this.$http.get('/api/getNewsList')//代替http://localhost:3000/getNewsList .then((res) => { this.newsList = res.data }, (err) => { console.log(err) })