将Curl调用API转换为XMLHttpRequest实现以获取JSON数据
Curl转XMLHttpRequest代码正确性验证
原始Curl请求
curl -X POST "http://bc.itg.ro:1239/api/ro/products" -H "accept: application/json" -H "X-Accept-Token: 7b030f02cce38a84d35122b5f353faq1" -H "Content-Type: application/json" -d "{ \"language_id\": 2, \"currency_id\": 4, \"filters\": { \"category_ids\": [ 56 ] }, \"current_page\": 1, \"limit\": 20}"
你编写的XMLHttpRequest代码
let xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { // Check if request is completed if (xhr.readyState == XMLHttpRequest.DONE) { // Do what needs to be done here console.log(xhr.response); } } // Set the request URL and request method xhr.open("POST", "http://bc.itg.ro:1239/api/ro/products"); // Set the `Content-Type` Request header xhr.setRequestHeader("accept", "application/json"); xhr.setRequestHeader("X-Accept-Token", "7b030f02cce38a84d35122b5f353faq1"); xhr.setRequestHeader("Content-Type", "application/json"); // Send the requst with Data xhr.send('{\"language_id\": 2, \"currency_id\": 4, \"filters\": { \"category_ids\": [ 56 ] }, \"current_page\": 1, \"limit\": 20}'); }
代码正确性分析与修正
你的代码整体逻辑符合Curl请求的转换要求,但存在几个细节问题需要调整:
- 语法错误:代码末尾多了一个多余的闭合大括号
},会导致JavaScript语法报错,必须删除。 - JSON字符串转义冗余:由于使用单引号包裹JSON字符串,内部的双引号无需转义,可简化写法避免出错:
更推荐用xhr.send('{"language_id": 2, "currency_id": 4, "filters": {"category_ids": [56]}, "current_page": 1, "limit": 20}');JSON.stringify()生成JSON字符串,彻底避免手动拼接的错误:const data = { language_id: 2, currency_id: 4, filters: { category_ids: [56] }, current_page: 1, limit: 20 }; xhr.send(JSON.stringify(data)); - 响应处理优化:添加
xhr.responseType = 'json'后,xhr.response会直接返回解析好的JSON对象,无需手动调用JSON.parse()。 - 请求成功判断:仅判断
readyState === XMLHttpRequest.DONE不代表请求成功,需结合HTTP状态码(200-299区间)确认请求是否正常完成,避免处理错误响应。
修正后的完整代码
let xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState === XMLHttpRequest.DONE) { if (xhr.status >= 200 && xhr.status < 300) { console.log('请求成功:', xhr.response); } else { console.error('请求失败:', xhr.status, xhr.statusText); } } }; xhr.open("POST", "http://bc.itg.ro:1239/api/ro/products"); xhr.responseType = 'json'; xhr.setRequestHeader("accept", "application/json"); xhr.setRequestHeader("X-Accept-Token", "7b030f02cce38a84d35122b5f353faq1"); xhr.setRequestHeader("Content-Type", "application/json"); const data = { language_id: 2, currency_id: 4, filters: { category_ids: [56] }, current_page: 1, limit: 20 }; xhr.send(JSON.stringify(data));
内容的提问来源于stack exchange,提问作者user20418879
相关产品推荐
相关产品推荐

