新版vue获取本地json文件数据

现在升级后的vue没有dev-server.js和dev-client.js,可以通过以下方式模拟后台数据:

1.找到webpack.dev.conf.js这个文件,在const portfinder = require(‘portfinder‘)后面添加以下代码:

 1 const express = require(‘express‘) 2 const app = express()//请求server 3 var appData = require(‘../data.json‘)//加载本地数据文件 4 var seller = appData.seller//获取对应的本地数据 5 var goods = appData.goods 6 var ratings = appData.ratings 7 var apiRoutes = express.Router() 8 app.use(‘/api‘, apiRoutes)//通过路由请求数据 9 10  devServer: {11 clientLogLevel: ‘warning‘,12  historyApiFallback: {13  rewrites: [14 { from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, ‘index.html‘) },15  ],16  },17 hot: true,18 contentBase: false, // since we use CopyWebpackPlugin.19 compress: true,20 host: HOST || config.dev.host,21 port: PORT || config.dev.port,22  open: config.dev.autoOpenBrowser,23  overlay: config.dev.errorOverlay24 ? { warnings: false, errors: true }25 : false,26  publicPath: config.dev.assetsPublicPath,27  proxy: config.dev.proxyTable,28 quiet: true, // necessary for FriendlyErrorsPlugin29  watchOptions: {30  poll: config.dev.poll,31  },32 //以下是添加的代码:33  before(app) {34 app.get(‘/api/seller‘, (req, res) => {35  res.json({36 errno: 0,37  data: seller38 })//接口返回json数据,上面配置的数据seller就赋值给data请求后调用39  }),40 app.get(‘/api/goods‘, (req, res) => {41  res.json({42 errno: 0,43  data: goods44  })45  }),46 app.get(‘/api/ratings‘, (req, res) => {47  res.json({48 errno: 0,49  data: ratings50  })51  })52 }53 54 55 },

 

2.运行npm run dev重启项目(注意,不重启,项目是不起效的):

 

?

3.在地址栏测试(以下就是获取到data.json里的数据):

?

?

?

相关文章