自学内容网 自学内容网

如何建一个前端项目,用来mock数据

1.下载所需的依赖,下面是package.json文件

{
  "name": "shop",
  "version": "1.0.0",
  "description": "shop mock",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start":"nodemon app.js"
  },
  "author": "Aimee",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.19.0",
    "btoa": "1.1.2",
    "commander": "^2.9.0",
    "connect-busboy": "0.0.2",
    "cookie-parser": "^1.4.3",
    "cors": "2.8.5",
    "cross-env": "^7.0.2",
    "express": "^4.13.4",
    "express-session": "^1.14.2",
    "express-urlrewrite": "^1.2.0",
    "http-proxy-middleware": "^1.0.1",
    "JSONPath": "0.11.2",
    "lodash": "^4.17.15",
    "node-fetch": "^2.6.11",
    "nodemon": "^2.0.7",
    "path-to-regexp": "^6.1.0"
  }
}

2.使用案例, 需要新建一个app.js文件,然后把下面的例子放进去,例子是模拟的一些请求(get, post)。

const express = require('express');
const path = require('path');
const http = require('http');
const _ = require('lodash');
const bodyParser = require('body-parser');
const router = express.Router();
const fs = require('fs');

const cors = require('cors');
const app = express();
app.use(express.static(path.join(__dirname, '/')));
app.use(bodyParser.json({ type: ["application/json", "application/csp-report", "text/plain"] }));

//解决cors跨域问题
app.use(cors());

router.route('/api/chat').post(function (req, res) {
  console.log("sigon:req:", req);
  res.json( require('./response/angularTest.json'));

});

const sigonFile = require('./response/sigon.json');
router.route('/api/sigon').post(function (req, res) {
  console.log("sigon:req:", req);
  res.json(sigonFile);

});

router.route('/api/getUserList').get(function (req, res) {
  console.log(req.query);
  const query = req.query;
  if (query['pagenum']=='1') {
    res.json(require('./response/getUserList1.json'));
  } else if (query['pagenum']=='2') {
    res.json(require('./response/getUserList2.json'));
  } else if (query['pagenum']=='3') {
    res.json(require('./response/getUserList3.json'));
  } else {
    res.json(require('./response/getUserList.json'));
  }
});

router.route('/api/updateUserStatus/:id/status/:status').post(function (req, res) {
  console.log(req.query);
  const query = req.query;
  if (query['pagenum']=='1') {
    res.json(require('./response/getUserList1.json'));
  } else if (query['pagenum']=='2') {
    res.json(require('./response/getUserList2.json'));
  } else if (query['pagenum']=='3') {
    res.json(require('./response/getUserList3.json'));
  } else {
    res.json(require('./response/getUserList.json'));
  }
});

app.use('', router);
const port = process.env.PORT || 7878;
http.createServer(app).listen(port, '0.0.0.0', () => {
  console.log('start', `${port}`);
})

3.文件目录
在这里插入图片描述


原文地址:https://blog.csdn.net/weixin_43795761/article/details/140423465

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!