一般模擬的資料只支援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:根據檔案的字尾名,呼叫不同的執行函式