React Native中如何在Axios Post请求中使用responseType: 'stream'?
解决React Native中Axios无法使用stream响应类型的问题
问题根源
React Native中Axios默认使用的XMLHttpRequest适配器不支持stream类型的responseType,而Node.js环境依赖HTTP适配器,因此能正常实现流式响应处理。
方案1:用React Native原生Fetch API实现流式处理
无需额外依赖,直接通过Fetch API读取流式响应:
const url = "url-of-chat-stream"; const fetchData = async () => { try { const requestData = { user_id: "11", question: "what are some inspirational books to read and some ideas to improve reading habits?" }; const response = await fetch(url, { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify(requestData) }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } // 获取可读流并逐块处理 const reader = response.body.getReader(); const decoder = new TextDecoder('utf-8'); while (true) { const { done, value } = await reader.read(); if (done) break; const chunk = decoder.decode(value, { stream: true }); console.log(chunk); } console.log('Streaming complete'); } catch (error) { console.error('Error:', error.message); } }; fetchData();
方案2:给Axios替换支持流式的适配器
如果想保留Axios的API风格,可使用第三方适配器实现流式支持:
- 安装依赖:
npm install axios-adapter-react-native-stream
- 修改Axios配置:
import axios from 'axios'; import createStreamAdapter from 'axios-adapter-react-native-stream'; const url = "url-of-chat-stream"; // 创建带流式适配器的Axios实例 const axiosInstance = axios.create({ adapter: createStreamAdapter() }); const fetchData = async () => { try { const requestData = { user_id: "11", question: "what are some inspirational books to read and some ideas to improve reading habits?" }; const response = await axiosInstance.post(url, requestData, { responseType: 'stream', headers: { accept: 'application/json', }, }); response.data.on('data', (chunk) => { if (chunk) { console.log(chunk.toString('utf-8')); } }); response.data.on('end', () => { console.log('Streaming complete'); }); } catch (error) { console.error('Error:', error.message); } }; fetchData();
注意事项
- 方案1轻量化,无额外依赖,适合多数场景;
- 方案2需注意第三方适配器与Axios版本的兼容性(适配Axios ^1.x版本);
- 确保后端返回的响应采用分块传输编码(Transfer-Encoding: chunked),否则无法实现流式处理。
内容的提问来源于stack exchange,提问作者Prince Dobariya
相关产品推荐
相关产品推荐

