typeerror:无法读取未定义的属性'getReader'

问题描述 投票:0回答:1
试图流式传输提取请求的响应时,我会收到以下错误:

"TypeError: Cannot read property 'getReader' of undefined".


更具体地说,我正在尝试使用OpenAI API,并且正在使用标准代码来流式传输在线发现的chatgpt响应(例如,this thissite

)。请参阅下面的代码: const API_KEY = "..."; // Private key goes here const API_URL = "https://api.openai.com/v1/chat/completions"; const getResponse = async () => { try { // Fetch data from openai as a post request fetch(API_URL, { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${API_KEY}`, }, body: JSON.stringify({ model: "gpt-3.5-turbo", messages: [ { role: "system", content: "10 words sentence", }, ], }), stream: true, }); const reader = response.body.getReader(); // <-- Problem is here ... } catch (error) { console.error(error); }

我能够在
stream: false

时成功获得(延迟)的响应,因此问题不是致电API。

loging到控制台的tofs tars
typeof response.body

,与误差匹配。

反应本机不支持Fetch API的响应主体中的
undefined
方法,该方法可在标准网络环境中获得。

替代解决方案:
react-native fetch-api openai-api
1个回答
0
投票

使用多填充:为了启用流媒体功能,开发人员可以使用多填充或替代库。例如,

getReader()
库提供了一个更合规的获取实现,以支持流。

Expo支持:如果您使用的是Expo,SDK已引入了对获取流的支持,可以在平台上提供更一致的体验。 rnfetchblob:一些开发人员转向诸如

react-native-fetch-api

库的库,该库支持流,但可能对远程URL和标题有限制。 解决方法:
    IMPLENTING POLYFILLS:您可以安装必要的多填充物并配置项目以在全球使用新的获取实现。这需要在您的输入文件中添加特定导入(例如,
  • rn-fetch-blob
    )。
    
    使用WebView:对于某些应用程序,使用WebView可能是处理流数据的解决方法,尽管此方法牺牲了某些本机功能。
  • 我建议您首先安装这些库
    index.js
      然后将它们导入
    1. npm install react-native-get-random-values react-native-url-polyfill [email protected] react-native-polyfill-globals
      
      
    2. index.js
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.