You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 16:25:33