index.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. const path = require("path");
  2. const fs = require("fs");
  3. /**
  4. * 读取本地mock数据
  5. * @param {*} req
  6. */
  7. function readMockData(req) {
  8. const { url, pathname, param, method } = req;
  9. return new Promise((resolve, reject) => {
  10. const filepath = path.resolve(__dirname, "./" + pathname + ".js");
  11. const fileExist = fs.existsSync(filepath);
  12. if (!fileExist) {
  13. const msg = `'${url}': mock data is not exist!`;
  14. reject({
  15. statusCode: 404,
  16. body: null,
  17. message: msg,
  18. });
  19. } else {
  20. try {
  21. delete require.cache[require.resolve(filepath)];
  22. const response = require(filepath);
  23. if (typeof response === "function") {
  24. const responseFun = response(req);
  25. resolve(responseFun);
  26. return;
  27. }
  28. resolve(response);
  29. } catch (err) {
  30. console.log("readMockError:", err);
  31. const msg = `'${url}': parse mock file error!`;
  32. reject({
  33. statusCode: 500,
  34. body: null,
  35. message: msg,
  36. });
  37. }
  38. }
  39. });
  40. }
  41. /**
  42. * express中间件,实现ajax mock数据功能
  43. * @param {*} app
  44. */
  45. module.exports = function mock(app) {
  46. app.all("*", function (req, res, next) {
  47. const method = req.method.toLocaleUpperCase();
  48. const param = method === "GET" ? req.query : req.body;
  49. // 请求日志打印
  50. console.log(req.method, req.url, param, Date.now());
  51. // 只处理ajax请求
  52. if (
  53. req.headers["x-requested-with"] === "XMLHttpRequest" ||
  54. req.path.indexOf("/api-mock") > -1
  55. ) {
  56. readMockData({
  57. url: req.url,
  58. pathname: req.path,
  59. param,
  60. method,
  61. })
  62. .then((response) => {
  63. res.status(response.statusCode || 200);
  64. res.setHeader("Content-Type", "application/json");
  65. res.end(JSON.stringify(response.body));
  66. })
  67. .catch((err) => {
  68. res.status(err.statusCode || 404);
  69. res.end();
  70. });
  71. } else {
  72. next();
  73. }
  74. });
  75. };