You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ExpressJS API 请求如何实现多分类切换及自定义关键词搜索

实现商品分类切换与关键词搜索的代码调整方案

核心调整思路

  • 从请求的req.query中提取前端传入的category_ids(分类ID,多个用英文逗号拼接)和keywords(搜索关键词)参数
  • 可按需增加基础参数合法性校验,避免非法格式传入下游接口
  • 将提取到的参数动态替换到下游接口的调用参数中即可

调整后的完整代码

app.get("/api/get-products", async (req, res) => {
  try {
    // 从请求query中提取前端传入的分类和关键词参数,默认设为空字符串
    const { category_ids = '', keywords = '' } = req.query;
    
    // 可选参数校验:分类ID仅允许数字和英文逗号
    const validCategoryReg = /^[\d,]*$/;
    if (!validCategoryReg.test(category_ids)) {
      return res.status(400).json({ code: 400, msg: '分类ID格式错误,多个请用英文逗号分隔' });
    }

    const queryResult = await client.execute('affiliate.product.query', {
      'app_signature':'mcc',
      'category_ids': category_ids, // 动态替换为前端传入的分类ID
      'keywords': keywords, // 动态替换为前端传入的搜索关键词
      'target_currency':'USD',
      'target_language':'EN',
    });

    // 返回查询结果给前端
    res.json({ code: 200, data: queryResult, msg: '查询成功' });
  } catch (error) {
    console.error('商品查询接口错误:', error);
    res.status(500).json({ code: 500, msg: '商品查询失败' });
  }
});

前端调用示例

需要切换分类或者修改搜索关键词时,直接在接口url的query参数里传对应值即可:

  • 查分类ID为101、关键词为hoodie的商品:http://localhost:3009/api/get-products?category_ids=101&keywords=hoodie
  • 同时查分类ID为101、102、103的所有商品(无搜索关键词):http://localhost:3009/api/get-products?category_ids=101,102,103&keywords=

内容的提问来源于stack exchange,提问作者Shaiful Rizal Shaharudin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 09:24:04