vue-cli(版本更新),由原來的2.8.1升級為2.9.1。主要改變是原來在build文件夾下的dev-server.js刪掉了,增加了webpack.dev.conf.js。
所以這次講的都是基於2.9.1 在webpack.dev.conf.js 添加.對於這些服務器配置,如果設置后,一定要重啟然后cnpm/npm run dev。
1.找到 bulid/webpack.dev.conf.js 文件,在該文件最后添加以下語句:
var port = process.env.PORT || config.dev.port
const express = require('express')
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('/api', apiRouter);
apiServer.listen(port+1, function (err) {
if (err) {
console.log(err)
return
}
console.log('Listening at http://localhost:'+(port+1)+'\n');
})
2.在index.html同級目錄中添加 db.json 文件

db.json數據如下:
{
"login": {
"username": "yudongdong",
"userId": 123123
},
"getPrice": {
"amount": 678
},
"createOrder": {
"orderId": "6djk979"
}
}
3.在 config/index.js 文件中兩處可修改位置如下:

4.運行 npm run dev
訪問localhost:3000,可顯示項目頁面
訪問localhost:3000/api/login,可以訪問模擬數據
也可以訪問localhost:3001/api/login,可以訪問模擬數據
5.npm install vue-resource --save ,即可訪問模擬服務器中的數據接口

《===========這樣就可以獲取模擬接口訪問數據並渲染出來了。==================》
