TypeScript中使用Axios调用Steam市场接口返回400错误请求问题排查
TypeScript中使用Axios调用Steam市场接口返回400错误请求问题排查
嘿,我仔细看了你的问题,浏览器和Python请求都能正常拿到数据,唯独Axios返回400,这种情况大概率是Axios的默认配置或者请求头细节和Steam服务器的要求不匹配。我给你梳理几个可能的排查方向和解决办法:
1. 清理Axios自动添加的不规范请求头
从你贴的错误响应里能看到,Axios自动给请求加了Content-Type: undefined这个字段,Steam的服务器对这类不规范的请求头可能会直接拒绝。你可以手动指定合规的Content-Type,或者删掉这个多余的头:
import axios from "axios"; let market_name: string = "★ M9 Bayonet | Marble Fade (Factory New)"; const instance = axios.create({ baseURL: "https://steamcommunity.com/market/pricehistory/", headers: { "Cookie": "sessionid=XXX; steamLoginSecure=76XXXXXXXXXXXHzCA", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36", "Accept": "application/json, text/plain, */*", "Accept-Encoding": "gzip, deflate, br", "Connection": "keep-alive", "Content-Type": "application/x-www-form-urlencoded" // 手动指定合规的内容类型 }, params: { "appid": "730", "market_hash_name": market_name, }, transformRequest: [(data, headers) => { // 移除自动添加的多余请求头 delete headers.common['Content-Type']; return data; }] }); instance.get() .then((response) => { console.log("Respone from API:", response.data); }) .catch((error) => { console.error("Error", error); });
2. 手动编码参数并直接拼接URL
虽然Axios会自动编码参数,但像★这种特殊字符的编码逻辑可能和浏览器略有差异。你可以手动用encodeURIComponent处理参数,直接拼到URL里绕过Axios的参数处理:
import axios from "axios"; let market_name: string = "★ M9 Bayonet | Marble Fade (Factory New)"; const encodedMarketName = encodeURIComponent(market_name); const requestUrl = `https://steamcommunity.com/market/pricehistory/?appid=730&market_hash_name=${encodedMarketName}`; axios.get(requestUrl, { headers: { "Cookie": "sessionid=XXX; steamLoginSecure=76XXXXXXXXXXXHzCA", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36", "Accept": "application/json, text/plain, */*", "Accept-Encoding": "gzip, deflate, br", "Connection": "keep-alive" } }) .then((response) => { console.log("Respone from API:", response.data); }) .catch((error) => { console.error("Error", error); });
3. 再次验证Cookie的完整性
你提到Cookie是有效的,但还是建议再对比浏览器开发者工具里的Cookie:确保sessionid和steamLoginSecure完全一致,没有多余空格、字符截断的情况——Steam对Cookie的校验非常严格,哪怕少一个字符都会导致请求失败。
4. 强制使用XHR适配器
Axios默认会根据环境自动选择适配器(xhr/http/fetch),有时候fetch适配器的请求行为和浏览器原生请求有细微差别。你可以强制指定使用XHR适配器,模拟浏览器的请求逻辑:
const instance = axios.create({ baseURL: "https://steamcommunity.com/market/pricehistory/", headers: { // 你的请求头配置 }, params: { // 参数配置 }, adapter: require('axios/lib/adapters/xhr') // 强制使用XHR适配器 });
另外一个小技巧:你可以在浏览器里把成功的请求导出为代码(Chrome右键请求→Copy→Copy as Node.js fetch),然后转换成Axios格式,对比自己的代码和导出代码的差异,能快速定位问题点。
备注:内容来源于stack exchange,提问作者Limes
相关产品推荐
相关产品推荐

