3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

axiosのNettwork ErrorでAPIからデータが取得できない

Posted at

環境

  • Macbook Air 2020
  • react 18.0.0
  • react-native 0.69.4
  • expo 46.0.6
  • React Native Debugger 0.13.0
  • iPhone12 mini
  • ios 15.6

1.状況

トレーニングマシン予約アプリを作成中、React NativeにてaxiosでAPI(Laravel)からジム一覧データを取得し、一覧表示させている。
動作確認のため、Expo Goアプリを使用し自分のiPhoneでアクセスしたところ、Nettwork Error が出ておりAPIからデータが取得できていなかった。
(React Native Debuggerではコンソールでデータが取得できていることは確認済み)

Gym.tsx
useEffect(() => {
  getGymAll();
}, []);

/**
 * 登録している全ジムデータを取得
 */
const getGymAll = async () => {
  try {
    const { data } = await axios.get(`http://loalhost/api/gym`);
    setGyms(data);
    console.log(data);
  } catch (error) {
    console.log(error.message);
  }
}

アクセスした際に getGymAll メソッドが実行され、取得したデータをステートにセットしている。

2.エラー内容

Axios Error : "Nettwork Error"

3.調査

axiosの書き方を変えてみる

下記記事を参考にコードを修正してみるも変化なし。

https://github.com/axios/axios/issues/3192

Gym.tsx
await axios.get(`http://localhost/api/gym`, {
  headers: {
    'Content-type': 'Application/json',
    'Accept': 'Application/json',
  },
  data: {},
})

LaravelのCORS設定を有効にしてみる

下記記事を参考に設定してみるも変化なし。

https://takabus.com/tips/341/#toc2

4.原因

http にリクエストを送っているのが原因のよう。

https://stackoverflow.com/questions/38418998/react-native-fetch-network-request-failed

記事の中で 「iOSはデフォルトでHTTPリクエストを許可しておらず、HTTPSのみ許可している」 との記載があった。

The problem here is that iOS does not allow HTTP requests by default, only HTTPS.
ここで問題となるのは、iOSはデフォルトでHTTPリクエストを許可しておらず、HTTPSのみ許可していることです。

5.解決策

egrok を使用し、 https://XXXXXXXX.ngrok.io アクセスしたらlocalhost にフォワーディングさせるようにした。

  • egrokをインストール

https://ngrok.com/download

  • egrokの設定

https://qiita.com/miriwo/items/8c1e6550a5ab279d60b5

  • egrok起動
ngrok http 80

起動すると Forwording https://XXXXXXXX.ngrok.io -> localhost と出てくるのでコード内の http://localhost の箇所を https://XXXXXXXX.ngrok.io に変更する。

Gym.tsx
useEffect(() => {
  getGymAll();
}, []);

/**
 * 登録している全ジムデータを取得
 */
const getGymAll = async () => {
  try {
    const { data } = await axios.get(`https://XXXXXXXX.ngrok.io/api/gym`);
    setGyms(data);
    console.log(data);
  } catch (error) {
    console.log(error.message);
  }
}

データが取得できた。

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?