前端项目使用 json-server模拟数据

使用 json-server模拟数据:

1. 安装 json-server 依赖

npm install -g json-server

2. 在 package.json 的 scripts 中添加如下命令

json-server --watch db.json --port 4000

在这里插入图片描述

3. 编写 server.js 文件, 下面是 server.js 文件内容参考模板

const jsonServer = require('json-server');
const server = jsonServer.create();
const router = jsonServer.router('db.json');
const middlewares = jsonServer.defaults();

server.use(middlewares);

server.get('/xxx/list/get', (req, res) => {
  const db = router.db;
  const obj = db.get('urlList').value();
  res.jsonp(obj);
});

server.get('/xxx/:id', (req, res) => {
  const { id } = req.params;
  let api = "";
  if (id === '40001') {
    api = "xxxId";
  } else {
    api = "commonRes";
  }
  const db = router.db;
  const obj = db.get(api).value();
  res.jsonp(obj);
});

server.get('/privilege/sirius/one/privilegeandrole/list', (req, res) => {
  const { uid } = req.query;
  let api = "";
  if (uid === 'xxxx4') {
    api = "xxxxList";
  } else {
    api = "commonRes";
  }
  const db = router.db;
  const obj = db.get(api).value();
  res.jsonp(obj);
});

server.post('/ai/service/v2/recognize/table', (req, res) => {
  const db = router.db;
  const obj = db.get("recognizeTable").value();
  res.jsonp(obj);
});


// 自定义路由
server.get('/custom-route', (req, res) => {
  res.jsonp({ message: 'This is a custom route' });
});

// 自定义路由带参数
server.get('/posts/:id/comments', (req, res) => {
  const { id } = req.params;
  const db = router.db; // 使用 lowdb 来访问数据
  const comments = db.get('comments').filter({ postId: parseInt(id) }).value();
  res.jsonp(comments);
});

// 自定义路由做一些数据处理
server.post('/create-post', (req, res) => {
  const { title, content } = req.body;
  if (!title || !content) {
    res.status(400).jsonp({ error: 'Title and content are required' });
    return;
  }

  const newPost = { id: Date.now(), title, content };
  const db = router.db;
  db.get('posts').push(newPost).write();

  res.status(201).jsonp(newPost);
});

// 使用 json-server 默认的路由处理数据
server.use(router);

// 启动服务器
server.listen(3004, () => {
  console.log('JSON Server is running on http://localhost:3004');
});

4. 准备 db.json 文件用于模拟后端数据返回,下面是 db.json 模板

{
  "commonRes": {
    "code": 0,
    "msg": "成功",
    "data": {}
  },
  "authList": {
    "code": 0,
    "msg": "成功",
    "data": [
      {
        "id": 1111,
        "name": "xxxx",
        "code": null,
        "status": 2,
        "createTime": "2033-06-05 11:032:17",
        "updateTime": null
      }
    ]
  }
}

5. 配置代理转发到 json-server

proxy.js

module.exports = {
	'/api/**': {
	    type: 'proxy',
	    // 正式环境
	    // target: 'https://production.api.com',
	    // 本地环境
	    target: 'http://localhost:4000'
	    changeOrigin: true,
	    
	    onProxyReq: (proxyReq, req, res) => {
	      // 打印请求的原始路径
	      console.log(`Request Path: ${req.originalUrl}`);  
	      // 打印代理后的真实路径
	      console.log(`Proxy to: ${proxyReq.protocol}//${proxyReq.host}${proxyReq.path}`);  	
	    }
	  },
	  
	  '/mock': {
	    target: 'http://localhost:4000',
	    changeOrigin: true,
	    pathRewrite: { '^/mock': '' }
	  }
}

6. 启动 json-server

在命令行终端直接执行 npm server, 将会运行配置在 package.json 的 scripts 中的 json-server --watch db.json --port 4000

或者

在命令行终端执行 node server.js , 默认将会监听 3004 端口,这样启动的话,上面的 proxy.js 文件也需要将代理端口改为 3004, 如下:

proxy.js

module.exports = {
	'/api/**': {
	    type: 'proxy',
	    // 正式环境
	    // target: 'https://production.api.com',
	    // 本地环境
	    target: 'http://localhost:3004'
	    changeOrigin: true,
	    
	    onProxyReq: (proxyReq, req, res) => {
	      // 打印请求的原始路径
	      console.log(`Request Path: ${req.originalUrl}`);  
	      // 打印代理后的真实路径
	      console.log(`Proxy to: ${proxyReq.protocol}//${proxyReq.host}${proxyReq.path}`);  	
	    }
	  },
	  
	  '/mock': {
	    target: 'http://localhost:3004',
	    changeOrigin: true,
	    pathRewrite: { '^/mock': '' }
	  }
}

到此就能将页面请求以 /api/** 以及 /mock 开头的接口转发到 json-server 中去了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值