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

Node.js如何获取GET查询字符串参数 动态设置商品接口查询关键词

代码修改方案

你只需要把硬编码的关键词替换为从请求查询参数中读取的值即可,修改后的完整代码如下:

app.get("/api/get-products/", async (req, res) => {
  // 读取URL中的keywords查询参数,无传参时默认使用beauty作为兜底
  const inputKeywords = req.query.keywords || 'beauty';

  // 可选:要求必须传keywords参数时打开下方注释
  // if (!req.query.keywords) {
  //   return res.status(400).send({ error: '请传入必填的keywords查询参数' });
  // }

  client.execute('aliexpress.affiliate.product.query', {
    'app_signature':'maarifahmall',
    // 'category_ids':'111,222,333',
    'fields':'commission_rate,sale_price',
    'keywords': inputKeywords,
    'max_sale_price':'100',
    'min_sale_price':'15',
    'page_no':'1',
    'page_size':'50',
    'platform_product_type':'ALL',
    'sort':'SALE_PRICE_ASC',
    'target_currency':'USD',
    'target_language':'EN',
    'tracking_id':'maarifahmall',
    'ship_to_country':'US',
    'delivery_days':'3'
  }, 
  function(error, response) {
    if (!error) {
      res.send(response['resp_result']);
    } else {
      res.status(500).send(error);
    }
  })
});

核心修改点

  • 新增变量读取查询参数:Express框架中GET请求的URL查询参数会自动挂载到req.query对象上,直接通过req.query.keywords就能拿到你在URL中传入的underwear值
  • 替换硬编码关键词:把原来写死的'beauty'替换为上面读取到的参数值,支持动态查询
  • 可选增加参数校验:如果接口要求必须传入关键词,开启注释的校验逻辑即可,避免无参数时请求异常
  • 优化错误返回状态码:请求出错时返回500状态码,更符合HTTP接口规范

修改后重启服务,访问http://localhost:3009/api/get-products/?keywords=underwear即可获取对应关键词的商品查询结果。

内容的提问来源于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.26 18:48:02