🪦
axumでCORSを解決する方法
はじめに
APIサーバをaxumで実装していた際にCORS問題で詰まったので、備忘録として残します。
CORS設定
axumが入っている前提となります。
以下のようにCORS設定をするだけで終わりです。
※Cargo.tomlで他に必要なcrateは省略しています。
Cargo.toml
[dependencies]
axum = "0.8.1"
tower-http={version="0.6.2", features=["cors"]}
main.rs
use axum::{http::HeaderValue, routing::get, Router};
use tower_http::cors::CorsLayer;
let cors = CorsLayer::new().allow_origin(["http://localhost:3000".parse::<HeaderValue>().unwrap()]);
let app = Router::new()
.route("/", get(|| async { "Hello, Axum!!!" }))
.layer(cors);
CORSのヘッダーを追加するミドルウェアを追加するレイヤーの設定です。
許可するヘッダーの値をallow_originで追加します。
配列形式なので複数設定可能です。
let cors = CorsLayer::new().allow_origin(["http://localhost:3000".parse::<HeaderValue>().unwrap()]);
(参考) https://docs.rs/tower-http/latest/tower_http/cors/struct.CorsLayer.html
上で作ったCORSの設定レイヤーをルーターに適用します。
個人的にちょっとつまずいたこととなのですが、必ず、route()の後に追加するするようにしましょう。
let app = Router::new()
.route("/", get(|| async { "Hello, Axum!!!" }))
.layer(cors);
これだけでCORS設定ができるようになります。
Discussion