- 在根目录建mock文件夹
在apiroutes.js中代码如下
var express = require('express') var apiRoutes = express.Router(); var home = require('./mockdata/home.json'); var daily = require('./mockdata/daily.json');; apiRoutes.get('/home', function (req, res) { res.json(home); }); apiRoutes.get('/daily', function (req, res) { res.json(daily); });
编辑build文件夹中dev-server.js文件中,增加
var apiRoutes = require('../mock/apiroutes.js') app.use('/api', apiRoutes);整体结构如下
var port = process.env.PORT || config.dev.port // automatically open browser, if not set will be false var autoOpenBrowser = !!config.dev.autoOpenBrowser // Define HTTP proxies to your custom API backend // https://github.com/chimurai/http-proxy-middleware var proxyTable = config.dev.proxyTable var app = express() var compiler = webpack(webpackConfig) var apiRoutes = require('../mock/apiroutes.js') app.use('/api', apiRoutes); var devMiddleware = require('webpack-dev-middleware')(compiler, { publicPath: webpackConfig.output.publicPath, quiet: true }) var hotMiddleware = require('webpack-hot-middleware')(compiler, { log: () => {} }) // force pages reload when html-webpack-plugin template changes compiler.plugin('compilation', function (compilation) { compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) { hotMiddleware.publish({ action: 'reload' }) cb() }) })
请求数据的时候,如下
this.axios.get('api/vocality').then(res => { }).catch(err => { })