赞
踩
当使用fetch
或axios
发出带有参数的GET请求并希望将响应类型设置为Blob
时,可以在请求配置中添加查询参数以及指定响应类型。以下是两个库的具体示例:
async function fetchBlobWithParams(url, params) { const queryString = Object.keys(params) .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`) .join('&'); const fullUrl = `${url}?${queryString}`; try { const response = await fetch(fullUrl); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const blob = await response.blob(); return blob; } catch (error) { console.error('There was a problem with the fetch operation:', error); } } // 使用示例 const params = { id: 123, type: 'image' }; fetchBlobWithParams('https://example.com/somefile', params) .then(blob => { const url = URL.createObjectURL(blob); console.log('Blob URL:', url); }) .catch(error => console.error(error));
const axios = require('axios'); async function axiosGetBlobWithParams(url, params) { try { const response = await axios.get(url, { params, responseType: 'blob', }); return response.data; // Blob对象 } catch (error) { console.error('There was a problem with the axios request:', error); } } // 使用示例 const queryParams = { postId: 456, format: 'pdf' }; axiosGetBlobWithParams('https://example.com/files', queryParams) .then(blob => { const url = URL.createObjectURL(blob); console.log('Blob URL:', url); }) .catch(error => console.error(error));
在这两个示例中,我们向请求URL添加了查询参数,并保持了将响应体处理为Blob
类型的能力。这样,你就可以根据需要传递参数,并处理返回的二进制数据了。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。