简单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, 看了一下这是一个未完成的项目, 感兴趣的话, 可以动手完善一下,

下面是一些程序的截图

相关推荐
gnip4 分钟前
vite和webpack打包结构控制
前端·javascript
excel25 分钟前
在二维 Canvas 中模拟三角形绕 X、Y 轴旋转
前端
阿华的代码王国1 小时前
【Android】RecyclerView复用CheckBox的异常状态
android·xml·java·前端·后端
一条上岸小咸鱼1 小时前
Kotlin 基本数据类型(三):Booleans、Characters
android·前端·kotlin
Jimmy1 小时前
AI 代理是什么,其有助于我们实现更智能编程
前端·后端·ai编程
ZXT1 小时前
promise & async await总结
前端
Jerry说前后端1 小时前
RecyclerView 性能优化:从原理到实践的深度优化方案
android·前端·性能优化
画个太阳作晴天1 小时前
A12预装app
linux·服务器·前端
喂完待续1 小时前
Apache Hudi:数据湖的实时革命
大数据·数据仓库·分布式·架构·apache·数据库架构
7723892 小时前
解决 Microsoft Edge 显示“由你的组织管理”问题
前端·microsoft·edge