mock.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import express from "express";
  2. import path from "path";
  3. import bodyParser from 'body-parser'
  4. import * as fs from "fs";
  5. import { fileURLToPath } from 'url';
  6. import fileUpload from 'express-fileupload'
  7. const __filename = fileURLToPath(import.meta.url);
  8. const __dirname = path.dirname(__filename);
  9. const staticDir = path.resolve(__dirname, "test");
  10. const publicDir = path.resolve(__dirname, "../dist");
  11. let startup = false;
  12. export async function createServer(port) {
  13. if (startup) {
  14. return;
  15. }
  16. const app = express();
  17. app.use(express.static(staticDir));
  18. console.log(publicDir)
  19. app.use(express.static(publicDir));
  20. app.use(bodyParser({ limit: '200mb' }))
  21. app.use(fileUpload({createParentPath: true}))
  22. app.listen(port);
  23. startup = true;
  24. app.use((req, res, next) => {
  25. const paths = req.url.split("/")
  26. const scene = paths[1]
  27. const filename = paths[paths.length - 1]
  28. const p = path.resolve(staticDir, scene, "./attach", filename)
  29. if (req.url.includes("/upload")) {
  30. return next()
  31. } else {
  32. fs.writeFileSync(p, JSON.stringify(req.body))
  33. }
  34. res.json({code: 0, msg: 'ok'})
  35. })
  36. app.post("/:sceneCode/upload", (req, res) => {
  37. const file = (req).files.file
  38. const relUrl = `/attach/upload/${file.name}`
  39. const absUrl = path.resolve(staticDir, `./${req.params.sceneCode}/${relUrl}`)
  40. console.log("上传图片完成路径为", relUrl)
  41. file.mv(absUrl, err => {
  42. if (err) {
  43. res.status(404)
  44. res.json({code: 1, msg: 'ok'})
  45. } else {
  46. res.json({code: 0, msg: 'ok', data: relUrl})
  47. }
  48. })
  49. })
  50. console.log("模拟环境已开启");
  51. }