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

如何通过JavaScript从AWS S3链接获取JSON并转换为JS对象

如何从AWS Transcribe生成的S3自动下载链接获取JSON对象?

我有一个指向AWS S3存储桶的链接,点击后会自动下载所需的JSON文件(该JSON不会在网页上直接显示),此链接来自AWS Transcribe。我尝试使用以下JavaScript函数获取数据但未成功,请问如何从该链接获取JavaScript对象?

function httpGetAsync(theUrl, callback) { 
  var xmlHttp = new XMLHttpRequest(); 
  xmlHttp.onreadystatechange = function() { 
    if (xmlHttp.readyState == 4 && xmlHttp.status == 200) callback(xmlHttp.responseText); 
  } 
  xmlHttp.open("GET", theUrl, true); // true for asynchronous 
  xmlHttp.send(null); 
}

问题分析与解决思路

这种自动下载的S3链接一般是预签名URL,你遇到的问题大概率和跨域限制、响应头配置或者请求逻辑不完善有关,下面分情况给你解决方案:

1. 先排查最常见的跨域(CORS)问题

如果你的代码是在浏览器环境下运行,S3桶默认会拦截跨域请求。你需要先在AWS S3控制台配置桶的CORS规则:

  • 进入S3存储桶的「权限」标签,找到「跨域资源共享(CORS)」
  • 添加类似以下的配置(替换成你的前端域名,本地开发可以暂时用*,生产环境一定要限制具体域名):
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>https://your-frontend-domain.com</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>

2. 完善你的XMLHttpRequest代码

你的原代码只处理了200状态码,没考虑重定向(S3预签名URL可能会返回302),也没做JSON解析。修改后的代码如下:

function httpGetAsync(theUrl, callback) { 
  var xmlHttp = new XMLHttpRequest(); 
  xmlHttp.onreadystatechange = function() { 
    if (xmlHttp.readyState == 4) {
      // 处理200成功和302重定向
      if (xmlHttp.status === 200 || xmlHttp.status === 302) {
        if (xmlHttp.status === 302) {
          // 自动跟随重定向链接
          const redirectUrl = xmlHttp.getResponseHeader('Location');
          return httpGetAsync(redirectUrl, callback);
        }
        // 解析响应为JSON对象
        try {
          const jsonObj = JSON.parse(xmlHttp.responseText);
          callback(null, jsonObj);
        } catch (parseErr) {
          callback(new Error('JSON解析失败: ' + parseErr.message), null);
        }
      } else {
        callback(new Error(`请求失败,状态码:${xmlHttp.status}`), null);
      }
    }
  };
  // 显式开启重定向跟随
  xmlHttp.followRedirects = true;
  xmlHttp.open("GET", theUrl, true); 
  // 告诉服务器我们期望JSON响应
  xmlHttp.setRequestHeader('Accept', 'application/json');
  xmlHttp.send(null); 
}

// 调用示例
httpGetAsync('你的S3预签名链接', function(err, data) {
  if (err) {
    console.error('获取数据失败:', err);
    return;
  }
  console.log('解析后的JSON对象:', data);
});

3. 改用更现代的Fetch API(推荐)

Fetch API语法更简洁,对重定向和错误处理更友好:

async function getS3TranscribeJson(url) {
  try {
    const response = await fetch(url, {
      method: 'GET',
      redirect: 'follow' // 自动跟随重定向
    });
    if (!response.ok) {
      throw new Error(`请求失败,状态码:${response.status}`);
    }
    // 即使响应头设置了attachment,依然可以直接解析JSON
    const jsonData = await response.json();
    return jsonData;
  } catch (err) {
    console.error('获取JSON失败:', err);
    throw err;
  }
}

// 调用示例
getS3TranscribeJson('你的S3预签名链接')
  .then(transcribeData => console.log('转录JSON数据:', transcribeData))
  .catch(err => console.error(err));

额外注意点

  • 确认你的预签名URL没有过期(AWS预签名URL默认有效期1小时)
  • 如果是在Node.js环境运行,不需要考虑CORS限制,直接用上述代码或者axios等库请求即可

内容的提问来源于stack exchange,提问作者Victoria Cabales

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:22:29