我需要通过将结果流式传输到CSV文件来从端点下载查询结果。这是为了支持一次通过浏览器发送大量结果集。
有没有办法在React App的上下文中使用Axios来完成此任务?
我看过fetch(),知道它具有以下特征:
除ReadableStream响应类型外,其他所有列出的特征都是不允许的。我将需要支持IE11,并允许拦截请求/读取HTTP状态以确定如何处理流量。
ReadableStream
fetch
// The promise returned by `fetch` rejects if the fetch was unable to make HTTP-request // e.g. network problems, or there’s no such site. // Abnormal HTTP-statuses, such as 404 or 500 do not cause an error. const results = await fetch(`${URL}/data`, { method: 'post', // HTTP POST to send query to server headers: { Accept: 'application/json, text/plain, */*', // indicates which files we are able to understand 'Content-Type': 'application/json', // indicates what the server actually sent }, body: JSON.stringify(query), // server is expecting JSON credentials: 'include', // sends the JSESSIONID cookie with the address }).then(res => res.json()) // turn the ReadableStream response back into JSON .then((res) => { if (res.ok) { // boolean, true if the HTTP status code is 200-299. console.log('response.ok!'); } else if (res.status === 401) { throw Error(`You are not authenticated. Please login.`); } else if (res.status === 403) { throw Error(`You are not authorized to access this data.`); } else { throw Error(`Request rejected with status ${res.status}`); } }) .catch((error) => { // catches error case and if fetch itself rejects error.response = { status: 0, statusText: 'Cannot connect. Please make sure you are connected to internet.', }; throw error; }); console.log(results);
axios
import ... const Api = axios.create({ baseURL: `${URL}`, withCredentials: true, }); // attach interceptors to requests and responses // these are defined elsewhere and imported Api.interceptors.request.use((request) => requestHandler(request)); Api.interceptors.response.use((response) => successHandler(response), (error) => errorHandler(error)); export default Api;
const query = {"selections":{"TABLE_A":["COLUMN1"]},"filters":[{"predicates":[]}],"joins":[],"sorts":[],"limit":100,"offset":0} const response = await Api.post('/data', query); // further transformations to response to get formatted csv results required
responseType: 'stream'
fs
当前 不 支持从浏览器流式传输响应:
https://github.com/axios/axios/issues/479
由于我们XMLHttpRequests在浏览器中进行处理,因此Axios仅限于设置的规范whatwg。:
XMLHttpRequests
whatwg
具体来说,以下是唯一受支持的类型:
enum XMLHttpRequestResponseType { "", "arraybuffer", "blob", "document", "json", "text" };
stream``responseType在axios中设置a被接受,但这会产生误导。xhr.js由于我们正在使用依赖于XMLHttpRequests的浏览器,因此该适配器将是隐式的。HttpRequest在服务器端进行,将允许axios使用http.js适配器。然后,您可以将其stream用作Node.js的ResponseType。
stream``responseType
xhr.js
http.js
stream
使用fetchAPI似乎是将a ReadableStream作为响应正文类型的唯一解决方案。