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

如何将给定的curl调用转换为JavaScript的XMLHttpRequest对象调用

curl转XMLHttpRequest实现示例

原curl请求

curl "https://test.api.amadeus.com/v1/security/oauth2/token" \
     -H "Content-Type: application/x-www-form-urlencoded" \
     -d "grant_type=client_credentials&client_id={client_id}&client_secret={client_secret}"

转换后的XMLHttpRequest实现

完整代码

const xhr = new XMLHttpRequest();

// 监听请求状态变化处理返回结果
xhr.onreadystatechange = () => {
  if (xhr.readyState === 4) {
    if (xhr.status >= 200 && xhr.status < 300) {
      console.log('请求成功:', JSON.parse(xhr.responseText));
    } else {
      console.error('请求失败:', xhr.status, xhr.responseText);
    }
  }
};

// 1. xhr.open() 方法:指定请求方法、接口地址、是否开启异步模式
xhr.open('POST', 'https://test.api.amadeus.com/v1/security/oauth2/token', true);

// 2. xhr.setRequestHeader() 方法:设置请求头,对应curl命令里的-H参数
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

// 3. xhr.send() 方法:传递请求体参数,对应curl命令里的-d参数
xhr.send('grant_type=client_credentials&client_id={client_id}&client_secret={client_secret}');

注意事项

  • 请把代码中的{client_id}和{client_secret}替换为你自己的实际接口凭证
  • 浏览器环境下调用该接口需要对方服务配置了CORS跨域规则,否则会触发跨域拦截导致请求失败
  • 接口返回的响应默认是字符串格式,需要通过JSON.parse()方法转换为JSON对象后再进行业务处理

内容的提问来源于stack exchange,提问作者Tolkienist Coder

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 15:36:00