Algolia POST请求报“Expecting value (near 1:1)”错误求助
解决Algolia POST请求返回"Expecting value (near 1:1)" 400错误
核心问题分析
- 请求体格式不匹配:Algolia的
/1/indexes/*/queries批量查询端点要求请求体为JSON格式,但你当前使用的是application/x-www-form-urlencoded的Content-Type,且payload是URL编码的损坏JSON,包含多余无效参数(如&=filters%3D&=query%3D),导致服务器无法解析为有效JSON。 - Payload语法错误:解码后的payload存在多处JSON语法问题:
- 多个请求对象的
params字段未正确闭合(比如第二个请求的params只写到analyticsTags就中断); - 存在大量重复参数(如重复的
clickAnalytics=true、facets=["*"]); - 末尾附加了不属于JSON结构的form参数,彻底破坏了JSON格式。
- 多个请求对象的
修复步骤
- 修正请求头:将
Content-Type设置为application/json,这是Algolia批量查询API的要求。 - 构建合法的JSON请求体:直接用Python的
json.dumps()生成标准JSON字符串,避免手动URL编码和语法错误。 - 清理无效参数:移除重复的查询参数,补全每个请求对象的必要字段,确保JSON结构完整。
修正后的代码示例
import http.client import json conn = http.client.HTTPSConnection("spe6j23569-dsn.algolia.net") # 构建合法的批量查询请求体 payload = json.dumps({ "requests": [ { "indexName": "prod_ftd_products", "params": "analyticsTags=[\"plp\",\"en-us\",\"desktop\"]&clickAnalytics=true&facets=[\"*\"]&filters=collections.handle:occasion_birthday_flowers AND hasSeoUrl:true AND isAddon:false&getRankingInfo=true&highlightPostTag=__/ais-highlight__&highlightPreTag=__ais-highlight__&maxValuesPerFacet=4&page=4&tagFilters=&hitsPerPage=4" }, { "indexName": "prod_ftd_products_query_suggestions", "params": "analyticsTags=&tagFilters=" }, { "indexName": "prod_ftd_products", "params": "analyticsTags=&tagFilters=" } ] }) headers = { 'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:120.0) Gecko/20100101 Firefox/120.0", 'Accept': "*/*", 'Accept-Language': "en-US,en;q=0.5", 'Accept-Encoding': "gzip, deflate, br", 'Referer': "https://www.ftd.com/", 'Content-Type': "application/json", # 修正为JSON类型 'Origin': "https://www.ftd.com", 'Connection': "keep-alive", 'Sec-Fetch-Dest': "empty", 'Sec-Fetch-Mode': "cors", 'Sec-Fetch-Site': "cross-site" } conn.request("POST", "/1/indexes/*/queries?x-algolia-agent=Algolia%20for%20JavaScript%20(4.19.1)%3B%20Browser%20(lite)%3B%20instantsearch.js%20(4.56.4)%3B%20react%20(18.2.0)%3B%20react-instantsearch%20(6.45.1)%3B%20react-instantsearch-hooks%20(6.45.1)%3B%20next.js%20(13.4.16)%3B%20JS%20Helper%20(3.14.0)&x-algolia-api-key=c6b60ecfe0cea00169ae8fcc041ccb95&x-algolia-application-id=SPE6J23569", payload, headers) res = conn.getresponse() data = res.read() print(data.decode("utf-8")) # 修正原代码中Decode的大小写错误
额外说明
- 原代码中
data.Decode("utf-8")是语法错误,Python字符串解码方法为小写的decode(),已在修正代码中修复。 - 批量查询的每个
params字段是URL编码的查询字符串,无需在JSON中再次编码,json.dumps()会自动处理字符串转义。
内容的提问来源于stack exchange,提问作者shourav singh
相关产品推荐
相关产品推荐

