Rust actix-webでプリフライトリクエストをチェックする

個人開発したアプリの宣伝
目的地が設定できる手帳のような使い心地のTODOアプリを公開しています。
Todo with Location

Todo with Location

  • Yoshiko Ichikawa
  • Productivity
  • Free

スポンサードリンク

actix-webでAccess-Control-Allow-Origin絡みのやつ。

actix-corsをmidleware利用する。

actix_cors - Rust


Cargo.toml
[dependencies]
actix-web = "3"
actix-cors = "0.5.3"


midlewareの登録

上記の実装例を見ながら、全originからのリクエストを許可する場合。

main.rs

use actix_web::{web, post, App, HttpServer, Result, HttpResponse};
use actix_web::http::header;
use actix_cors::Cors;


#[actix_web::main]
async fn main() -> std::io::Result<()> {
    std::env::set_var("RUST_LOG", "actix_web=info");
    env_logger::init();

    HttpServer::new(|| {
        let cors = Cors::default()
            .allowed_origin_fn(|origin, _req_head| {
                true
            })
            .allowed_methods(vec!["GET", "POST"])
            .allowed_headers(vec![header::AUTHORIZATION, header::ACCEPT])
            .allowed_header(header::CONTENT_TYPE)
            .supports_credentials()
            .max_age(3600);

        App::new()
            .wrap(cors)
            .service(index)
    })
    .bind("127.0.0.1:8082")?
    .run()
    .await
}


特定originのみ許可

特定originからの場合は、

let cors = Cors::default()
    .allowed_origin("http://localhost:8080")

のように書けばいいんだけど、port指定がある場合は、http://localhost:8080/のように末尾に/があると弾かれる。思わぬところでハマった。

何故にダメなんだと、

examples/main.rs at master · actix/examples · GitHub

こちらのサンプル実装をにらめっこして、ようやく気がついた笑

ちゃんちゃん