如何区分返回内容是文件流还是json数据?

145 阅读3分钟

如何区分返回内容是文件流还是 JSON 数据

在 Web 开发中,处理 API 响应时,常常需要根据返回内容的类型进行不同的处理。特别是当 API 可能返回文件流(如图片、PDF 等)或 JSON 数据时,正确区分这两者显得尤为重要。以下是几种有效的区分方法。

1. 检查 Content-Type 响应头

HTTP 响应的 Content-Type 头信息指示了返回内容的媒体类型。通过检查这个字段,可以有效判断返回的数据类型。

  • JSON 数据 通常会返回 application/jsontext/json
  • 文件流Content-Type 会根据文件类型不同而有所不同,例如:
    • 图片:image/jpegimage/png
    • PDF:application/pdf
    • 文档:application/mswordapplication/vnd.openxmlformats-officedocument.wordprocessingml.document

示例代码:

fetch('your-api-endpoint')
  .then(response => {
    const contentType = response.headers.get('Content-Type');
    if (contentType.includes('application/json')) {
      return response.json(); // 处理 JSON 数据
    } else {
      return response.blob(); // 处理文件流
    }
  })
  .then(data => {
    // 根据返回的类型进行后续处理
  });

2. 检查响应体的格式

有时 API 的响应可能未正确返回 Content-Type,这是需要根据响应体的内容进行判断。可以尝试解析内容:

  • JSON 数据 通常是合法的 JSON 格式,可以使用 try-catch 进行解析测试。
  • 文件流 通常是二进制文件,尝试解析时会抛出错误。

示例代码:

fetch('your-api-endpoint')
  .then(response => response.text()) // 先以文本形式读取
  .then(text => {
    try {
      const jsonData = JSON.parse(text); // 尝试解析为 JSON
      // 处理 JSON 数据
    } catch (error) {
      // 处理文件流
      const blob = new Blob([text]); // 将文本转为 Blob
    }
  });

3. 使用 response.blob()

如果你知道 API 可能返回的是文件流,可以直接使用 response.blob() 方法来处理。这样可以避免对 Content-Type 的依赖。

示例代码:

fetch('your-api-endpoint')
  .then(response => {
    if (response.ok) {
      return response.blob(); // 直接处理为 Blob
    }
    throw new Error('Network response was not ok.');
  })
  .then(blob => {
    // 处理文件流
  })
  .catch(error => {
    console.error('There has been a problem with your fetch operation:', error);
  });

4. 使用 Axios 进行请求

如果您使用 Axios 进行请求,可以通过配置 responseType 来处理不同的返回类型:

  • responseType: 'json' 用于处理 JSON 数据。
  • responseType: 'blob' 用于处理文件流。

示例代码:

axios.get('your-api-endpoint', { responseType: 'blob' })
  .then(response => {
    const contentType = response.headers['content-type'];
    if (contentType.includes('application/json')) {
      // 处理 JSON 数据
    } else {
      // 处理文件流
    }
  })
  .catch(error => {
    console.error('Error fetching data:', error);
  });

5. 处理错误与异常

在处理 API 响应时,一定要做好错误处理。例如,网络请求失败、解析 JSON 失败等情况,建议使用 try-catchcatch 语句来捕获异常,并进行相应的处理。

示例代码:

fetch('your-api-endpoint')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.headers.get('Content-Type').includes('application/json') 
      ? response.json() 
      : response.blob();
  })
  .then(data => {
    // 处理数据
  })
  .catch(error => {
    console.error('There was a problem with the fetch operation:', error);
  });

总结

区分返回内容是文件流还是 JSON 数据可以通过检查 Content-Type、响应体的格式、直接使用 Blob、使用 Axios 进行请求以及做好错误处理来实现。在实际开发中,可以根据具体情况选择合适的方法,以确保 API 响应能够被正确处理。