React Native for Rapid API 中的 fetch 方法网络请求失败

问题描述 投票:0回答:1

我正在开发一个反应原生应用程序。

我想调用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 代码片段,它可以直接工作。

我做错了什么?

javascript react-native fetch-api rapidapi
1个回答
1
投票

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>
© www.soinside.com 2019 - 2024. All rights reserved.