VUE中前端mock假数据的办法
使用vue-cli脚手架工具之后生存的目录下找到config\index.js文件替换其中dev字段的代码: dev: {// PathsassetsSubDirectory: 'static',assetsPublicPath: '/',proxyTable: {'/api': {target:...
·
使用vue-cli脚手架工具之后生存的目录下找到config\index.js文件
替换其中dev字段的代码:
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/api': {
target: 'http://localhost:8081/', // 通过本地服务器将你的请求转发到这个地址
changeOrigin: true, // 设置这个参数可以避免跨域
pathRewrite: {
'/api': '/'
}
},
},
// Various Dev Server settings
host: 'localhost', // can be overwritten by process.env.HOST
port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
autoOpenBrowser: false,
errorOverlay: true,
notifyOnErrors: true,
poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
// Use Eslint Loader?
// If true, your code will be linted during bundling and
// linting errors and warnings will be shown in the console.
useEslint: true,
// If true, eslint errors and warnings will also be shown in the error overlay
// in the browser.
showEslintErrorsInOverlay: false,
/**
* Source Maps
*/
// https://webpack.js.org/configuration/devtool/#development
devtool: 'cheap-module-eval-source-map',
// If you have problems debugging vue-files in devtools,
// set this to false - it *may* help
// https://vue-loader.vuejs.org/en/options.html#cachebusting
cacheBusting: true,
cssSourceMap: true
},
然后找到build\webpack.dev.conf.js文件 在末尾添加代码:
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('data.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(8081, function (err) {
if (err) {
console.log(err)
return
}
console.log('Listening at http://localhost:' + (8081) + '\n')
})
最后在更目录下新建data.json文件即为数据接口:
{
"ratings": [
{
"username": "3******c",
"rateTime": 1469281964000,
"deliveryTime": 30,
"score": 5,
"rateType": 0,
"text": "不错,粥很好喝,我经常吃这一家,非常赞,以后也会常来吃,强烈推荐.",
"avatar": "http://static.galileo.xiaojukeji.com/static/tms/default_header.png",
"recommend": [
"南瓜粥",
"皮蛋瘦肉粥",
"扁豆焖面",
"娃娃菜炖豆腐",
"牛肉馅饼"
]
}
]
}
更多推荐
已为社区贡献1条内容
所有评论(0)