Node.js中如何修改请求URL的keywords参数以获取不同接口返回结果
解决方案
1 修复路由参数不匹配问题
你当前代码定义的路由使用路径参数规则/api/get-products/:keywords,但给出的接口调用示例使用查询参数?keywords=naruto,二者不匹配会导致无法正常取到keyword参数,优先调整路由适配查询参数写法,兼容性更强。
2 实现每次返回不同结果的优化逻辑
可从三个维度实现差异化返回,你可以根据需求选择:
- 随机关键词:预设关键词池,无指定关键词时随机选取调用接口
- 随机页码:每次请求随机生成页码值,拉取不同页的商品数据
- 随机排序:接口返回商品列表后打乱顺序再返回给前端
修改后完整代码
// 预设关键词池,可自行扩充 const keywordPool = ['naruto', 'iphone case', 'sneaker', 'backpack', 'wireless headphone', 'yoga mat', 'gaming mouse'] // 路由调整为适配查询参数,匹配你给出的调用示例格式 app.get("/api/get-products", async (req, res) => { // 优先取请求传入的keywords,没有就从关键词池随机选 const targetKeyword = req.query.keywords || keywordPool[Math.floor(Math.random() * keywordPool.length)] // 随机生成1-10的页码,可根据实际业务调整范围 const randomPage = Math.floor(Math.random() * 10) + 1 client.execute('aliexpress.affiliate.product.query', { 'app_signature':'maarifahmall', // 'category_ids':'111,222,333', 'fields':'commission_rate,sale_price', 'keywords': targetKeyword, 'max_sale_price':'100', 'min_sale_price':'15', 'page_no': randomPage.toString(), '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) { const productList = response?.resp_result?.result?.products?.product || [] // 打乱商品列表顺序 const shuffledList = productList.sort(() => Math.random() - 0.5) response.resp_result.result.products.product = shuffledList res.send(response['resp_result']); } else { res.send(error); } }) });
修改后你可以直接用原有示例地址http://localhost:3009/api/get-products/?keywords=naruto调用,也可以不传keywords参数,接口会自动随机选关键词返回不同结果。
内容的提问来源于stack exchange,提问作者Shaiful Rizal Shaharudin
相关产品推荐
相关产品推荐

