"TypeError: Cannot read property 'getReader' of undefined".
)。请参阅下面的代码:
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
方法,该方法可在标准网络环境中获得。
替代解决方案:使用多填充:为了启用流媒体功能,开发人员可以使用多填充或替代库。例如,
getReader()
库提供了一个更合规的获取实现,以支持流。
Expo支持:如果您使用的是Expo,SDK已引入了对获取流的支持,可以在平台上提供更一致的体验。
rnfetchblob:一些开发人员转向诸如react-native-fetch-api
rn-fetch-blob
)。使用WebView:对于某些应用程序,使用WebView可能是处理流数据的解决方法,尽管此方法牺牲了某些本机功能。
index.js
npm install react-native-get-random-values react-native-url-polyfill [email protected] react-native-polyfill-globals
index.js