我正在开发一个反应原生应用程序。
我想调用RapidAPI,例如:
useEffect(() => {
fetch("https://jokes-by-api-ninjas.p.rapidapi.com/v1/jokes", {
method: "GET",
headers: {
'X-RapidAPI-Key': 'myapi',
'X-RapidAPI-Host': 'jokes-by-api-ninjas.p.rapidapi.com'
}
})
.then((response) => response.json())
.then((data) => {
console.log(data);
})
.catch((error) => console.log(error));
}, []);
我收到此错误:
[TypeError: Network request failed]
。
我也尝试过 axios 包并导致了同样的事情。
我使用了 Rapid API 中的 python 代码片段,它可以直接工作。
我做错了什么?
React Native 使用 fetch API,其行为可能与 Python 的 requests 库不同。尝试使用 React Native 中的 https 模块来发出请求。
安装
https
模块,然后
import https from 'https';
useEffect(() => {
const options = {
method: 'GET',
headers: {
'X-RapidAPI-Key': 'myapi',
'X-RapidAPI-Host': 'jokes-by-api-ninjas.p.rapidapi.com'
}
};
const req = https.request('https://jokes-by-api-ninjas.p.rapidapi.com/v1/jokes', options, (response) => {
let data = '';
response.on('data', (chunk) => {
data += chunk;
});
response.on('end', () => {
console.log(JSON.parse(data));
});
});
req.on('error', (error) => {
console.error(error);
});
req.end();
}, []);
这里的问题也可能是 iOS 默认情况下不允许 HTTP 请求,只允许 HTTPS。如果你想启用 HTTP 请求,请将其添加到你的 info.plist 中:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>