调用漫威API获取单个角色Agent Zero报409错误如何解决?
Marvel API查询单个角色409错误解决方法
错误原因
你修改后的baseUrl末尾已经携带了?name=Agent+Zero查询参数,后续拼接鉴权参数时又使用了?开头,导致最终请求URL出现两个?,参数格式非法,触发Marvel API的409参数冲突错误。
解决方法
有两种可行的修改方案:
方案1:按名称筛选请求
保留原始baseUrl格式,将name参数放到后续的参数拼接逻辑中:
const axios = require('axios'); const md5 = require('blueimp-md5'); const publickey = 'publickey'; const privatekey = 'privatekey'; const ts = new Date().getTime(); const stringToHash = ts + privatekey + publickey; const hash = md5(stringToHash); // baseUrl保留原始无参数格式 const baseUrl = 'https://gateway.marvel.com:443/v1/public/characters'; // 拼接时先加name参数,再拼接鉴权参数 const url = baseUrl + '?name=Agent%20Zero&ts=' + ts + '&apikey=' + publickey + '&hash=' + hash; async function getMarvel(){ const { data } = await axios.get(url); return data; }
这种方式会返回匹配名称的角色列表,因为Marvel角色名称唯一,返回结果里只会包含Agent Zero的数据。
方案2:按角色ID查询(更稳定)
你已经从全量列表中拿到了Agent Zero的角色ID为1009150,可以直接请求单个角色资源,不需要做名称筛选,匹配精度更高:
const axios = require('axios'); const md5 = require('blueimp-md5'); const publickey = 'publickey'; const privatekey = 'privatekey'; const ts = new Date().getTime(); const stringToHash = ts + privatekey + publickey; const hash = md5(stringToHash); // baseUrl后直接拼接角色ID const baseUrl = 'https://gateway.marvel.com:443/v1/public/characters/1009150'; const url = baseUrl + '?ts=' + ts + '&apikey=' + publickey + '&hash=' + hash; async function getMarvel(){ const { data } = await axios.get(url); return data; }
这种方式返回的结果直接是Agent Zero的详情数据,不需要额外从列表中提取。
内容的提问来源于stack exchange,提问作者Swayam Shah
相关产品推荐
相关产品推荐

