如何将给定的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
相关产品推荐
相关产品推荐

