前提
バックエンド: Actix Web(Rust)
モバイル: React Native
現象
export default function HomeScreen() {
const [text, setText] = useState("");
useEffect(() => {
fetch("http://localhost:8080/", {
headers: {
"Content-Type": "application/json",
},
})
.then(async (response) => {
setText(await response.text());
})
.catch((error) => {
console.log(error);
});
}, []);
return (
// 以下略
use actix_web::{get, post, web, App, HttpResponse, HttpServer, Responder};
#[get("/")]
async fn hello() -> impl Responder {
HttpResponse::Ok().body("Hello world!")
}
#[post("/echo")]
async fn echo(req_body: String) -> impl Responder {
HttpResponse::Ok().body(req_body)
}
async fn manual_hello() -> impl Responder {
HttpResponse::Ok().body("Hey there!")
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.service(hello)
.service(echo)
.route("/hey", web::get().to(manual_hello))
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}
上記のコードの際に、AndroidからAPIをfetchできなかった。([TypeError: Network request failed]
というエラーが出ていた)
ブラウザでhttp:localhost:8080
を叩いたり、http://127.0.0.1:8080
を叩く場合は問題なし。
解決方法
Actix Webでbindする値を"0.0.0.0", 8080
に変更し、
ReactNativeのコードではfetchする箇所を
http://192.168.40.31:8080/
上記のようにドメインをプライベートipアドレスにしたらAPIが取得できた。
参考
https://ja.stackoverflow.com/questions/94827/actix-web-%E3%81%A7%E8%B5%B7%E5%8B%95%E3%81%97%E3%81%9F%E3%82%B5%E3%83%BC%E3%83%90%E3%83%BC%E3%81%AB%E5%88%A5%E3%81%AE%E7%AB%AF%E6%9C%AB%E3%81%8B%E3%82%89%E3%82%A2%E3%82%AF%E3%82%BB%E3%82%B9%E3%81%A7%E3%81%8D%E3%81%AA%E3%81%84
https://qiita.com/1ain2/items/194a9372798eaef6c5ab