Flutterのローカル開発で、APIリクエストがSocketExceptionと怒られたときの対応
事象
- APIリクエストには
retrofit
を使用している -ローカル環境に対してつないでいる、Andoridのエミュレーター - リクエスト時に、
SocketException: OS Error: Connection refused, errno = 111, address = localhost, port = 37922
みたいなエラーになる - ローカルをcurlするとレスポンスが問題なく返ってくる
I/flutter (17987): ╔╣ Request ║ GET I/flutter (17987): ║ http://localhost:3000/api/v1/rooms/1 I/flutter (17987): ╚══════════════════════════════════════════════════════════════════════════════════════════ I/flutter (17987): I/flutter (17987): ╔╣ DioError ║ DioErrorType.DEFAULT I/flutter (17987): ║ SocketException: OS Error: Connection refused, errno = 111, address = localhost, port = 37922 I/flutter (17987): ╚══════════════════════════════════════════════════════════════════════════════════════════
調査
you're running the server locally and using the Android emulator, then your server endpoint should be 10.0.2.2:8000 instead of localhost:8000 as AVD uses 10.0.2.2 as an alias to your host loopback interface (i.e) localhost
対応
# 変更前 @RestApi(baseUrl: "http://localhost:3000/api/v1/") # 変更後 @RestApi(baseUrl: "http://10.0.2.2:3000/api/v1/")
にしたら行けた。謎。 今度原因を調べる。