简单mock server模拟用户请求给小程序提供数据

整理小程序代码时发现一此小程序离开了mock-server基本上没有办法显示了,因此用node,express来满足给小程序提供演示数据的功能

javascript 复制代码
const express = require('express');  
const { createCanvas, Image } = require('canvas');  
const fs = require('fs');  
const path = require('path');  
const app = express();  
const port = 3000;  
const querystring = require('querystring');  


function createImageFromPath(req, res) {

  const imagePath = req.path;  
  const match = imagePath.match(/\/(\d+)x(\d+)\.jpg/);  
  if (match) {  
    const [, widthStr, heightStr] = match;  
    const width = parseInt(widthStr, 10);  
    const height = parseInt(heightStr, 10);  
  
    if (isNaN(width) || isNaN(height)) {  
      return res.status(400).send('Invalid image dimensions');  
    }  

   
  
    const canvas = createCanvas(width, height);  
    const ctx = canvas.getContext('2d');  
  
    // 生成随机背景颜色  
    const randomColor = '#' + Math.floor(Math.random() * 16777215).toString(16);  
    ctx.fillStyle = randomColor;  
    ctx.fillRect(0, 0, width, height);  


    
  
    // 获取对比色  
    const contrastColor = getContrastColor(randomColor);  

      const queryParams = req.query.q;  
      console.log(queryParams);
        // 在图像上显示尺寸字样  
        const fontSize = 30; // 字体大小  
        let text = `${width}x${height}`; // 尺寸字样            
        if (queryParams) {  
          text = queryParams; // 如果查询参数不为空,使用查询参数的值  
        }  
        ctx.font = `${fontSize}px simsun`;  
        const metrics = ctx.measureText(text); // 测量文本尺寸  
        const x = (width - metrics.width) / 2; // 计算文本水平居中位置  
        const y = height / 2 + fontSize / 2; // 计算文本垂直居中位置  
    // 画描边  
   // ctx.strokeStyle = contrastColor;  
   // ctx.lineWidth = 10;  
   // ctx.strokeText(text, x, y);  
  
    // 画填充文本  
    ctx.fillStyle = contrastColor;  
    ctx.fillText(text, x, y);  
  
    // 画图像边框  
    ctx.strokeStyle = contrastColor;  
    ctx.lineWidth = 10; // 边框宽度  
    ctx.strokeRect(0, 0, width, height); // 画矩形边框  
  
    // 将canvas转换为Buffer对象  
    const buffer = canvas.toBuffer('image/jpeg');  
  
    // 设置响应头信息  
    res.setHeader('Content-Type', 'image/jpeg');  
    res.setHeader('Content-Disposition', 'inline; filename=generated.jpg');  
    res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');  
    res.setHeader('Pragma', 'no-cache');  
    res.setHeader('Expires', '0');  
  
    // 发送图片Buffer到响应中  
    res.send(buffer);  
  } else {  
    // 如果没有匹配到尺寸,则发送404错误  
    res.status(404).send('Not Found');  
  }  
}  
  
// 辅助函数:获取对比色  
function getContrastColor(color) {  
  // 将颜色字符串转换为RGB数组  
  const rgb = color.slice(1).match(/.{2}/g).map(byte => parseInt(byte, 16));  
  
  // 计算亮度  
  const luminance = (0.299 * rgb[0] + 0.587 * rgb[1] + 0.114 * rgb[2]) / 255;  
  
  // 根据亮度返回对比色  
  return luminance > 0.5 ? '#000000' : '#FFFFFF';  
}

  
  // 使用中间件处理所有以.jpg结尾的请求  
app.use(express.static(path.join(__dirname, 'public'))); // 假设你的静态文件在public文件夹中  
app.get(/\/(\d+)x(\d+)\.jpg/, createImageFromPath);  
app.get(/\*.jpg$/, (req, res) => {  
  res.status(404).send('Not Found');  
});  
  
  
app.get('/:filename', (req, res) => {  
  const fileName = req.params.filename;  
  const filePath = path.join(__dirname, `${fileName}.json`);  
  
  fs.readFile(filePath, 'utf8', (err, data) => {  
    if (err) {  
      if (err.code === 'ENOENT') {  
        // 文件不存在的错误  
        res.status(404).send('File not found');  
      } else {  
        // 其他类型的错误  
        res.status(500).send('Internal Server Error');  
      }  
      return;  
    }  
  
    res.setHeader('Content-Type', 'application/json');  
    res.send(data);  
  });  
});  
app.listen(port, () => {  
  console.log(`Server is running on port ${port}`);  
});

整理一个o2o行业 洗衣小程序时添加了一些演示数据,这个洗衣程序, 有充值页面, 在地图搜索洗衣机, 拖动地图时, 可以实时加载洗衣机, 可以绑定洗衣, 没有后台, 只有简单的mock server, 看了一下这是一个未完成的项目, 感兴趣的话, 可以动手完善一下,

下面是一些程序的截图

相关推荐
Samuel-Gyx33 分钟前
前端 CSS 样式书写与选择器 基础知识
前端·css
天天打码1 小时前
Rspack:字节跳动自研 Web 构建工具-基于 Rust打造高性能前端工具链
开发语言·前端·javascript·rust·开源
字节高级特工1 小时前
【C++】”如虎添翼“:模板初阶
java·c语言·前端·javascript·c++·学习·算法
db_lnn_20212 小时前
【vue】全局组件及组件模块抽离
前端·javascript·vue.js
Qin_jiangshan2 小时前
vue实现进度条带指针
前端·javascript·vue.js
菜鸟una2 小时前
【layout组件 与 路由镶嵌】vue3 后台管理系统
前端·vue.js·elementui·typescript
小张快跑。2 小时前
【Vue3】使用vite创建Vue3工程、Vue3基本语法讲解
前端·前端框架·vue3·vite
Zhen (Evan) Wang2 小时前
.NET 8 API 实现websocket,并在前端angular实现调用
前端·websocket·.net
星空寻流年3 小时前
css3响应式布局
前端·css·css3
Rverdoser3 小时前
代理服务器运行速度慢是什么原因
开发语言·前端·php