一般模拟的数据只支持get方式,为了支持post等方式,可以采用把api转到node的路由上来实现。
const express = require('express');
const app = express();
const apiRouters = express.Router();
// 模拟的数据的地址
const paths = require('./paths');
const appMockup = paths.appMockup;
apiRouters.all(‘/column’, function (req, res) {
const filepath = require.resolve(appMockup + '/column.json');
delete require.cache[filepath];
res.json(require(filepath));
});
apiRouters.all('/pie', function (req, res) {
const filepath = require.resolve(appMockup + '/pie.json');
delete require.cache[filepath];
res.json(require(filepath));
});
apiRouters.all('/trend', function (req, res) {
const filepath = require.resolve(appMockup + '/trend.json');
delete require.cache[filepath];
res.json(require(filepath));
});
module.exports = apiRouters;
// 使用方式
const express = require('express');
const app = express();
const apiRouters = require('./mockup');
app.use('/api', apiRoute
rs);
注: require函数及其辅助方法主要如下:
require(): 加载外部模块
require.resolve():将模块名解析到一个绝对路径
require.main:指向主模块
require.cache:指向所有缓存的模块
require.extensions:根据文件的后缀名,调用不同的执行函数