基于vue-cli (mock假数据)
2017-11-21 本文已影响0人
进击的小前端
有时候web前端需要一些假数据来进行模拟后台数据。基于vue-cli,我们就来演示一下如何模拟假数据,用到了 express,和 express.Router、
依旧废话不多说,直接上代码。

存放json文件
json文件内容例如(自己随便写的):
{
"seller":{
text:"我是seller"
},
"goods":{
text:"我是goods"
},
"ratings":{
text:"我是ratings"
}
}
需要在build里面修改一下dev-server文件:

然后进行修改文件:
//导入data.json文件
const appData = require("../data.json");
//存一下数据
const seller = appData.seller;
const goods = appData.goods;
const ratings = appData.ratings;
//创建express路由
const apiRoutes = express.Router();
//用路由接受一下 这里的/seller就是访问的地址
apiRoutes.get("/seller",(req,res)=>{
res.json({
errorNo:0,
seller
});
});
apiRoutes.get("/goods",(req,res)=>{
res.json({
errorNo:0,
goods
});
});
apiRoutes.get("/ratings",(req,res)=>{
res.json({
errorNo:0,
ratings
});
});
//这里需要用一下 "/api"这里是就在api/seller
app.use("/api",apiRoutes);
重新 npm run dev
按着下图访问 就能访问到数据了
(我这里是在谷歌商店上安装了读取json文件的插件,如果有兴趣的小伙伴也可以去安装一下,很强大,麻麻再也不用担心我看json文件咪眼睛了...)