tower-rs / tower-http

HTTP specific Tower utilities.
675 stars 156 forks source link

CorsLayer methods are limited to GET and HEAD. #494

Closed Ali-Javanmardi closed 2 months ago

Ali-Javanmardi commented 2 months ago

Bug Report

Version

tower-http = 0.5.2 axum = 0.7

Platform

Linux U41-DEV 6.9.4-arch1-1 #1 SMP PREEMPT_DYNAMIC Wed, 12 Jun 2024 20:17:17 +0000 x86_64 GNU/Linux

Crates

Description

My post request to axum server gets cors error "405 Method Not Allowed"

My axum server is running on http://localhost:8080 My front-end app (vuejs) is running on http://localhost:5173

my axum server should work as an api server.

First I read this example: https://github.com/tokio-rs/axum/blob/main/examples/cors/src/main.rs so I added CorsLayer to my routes in axum routes.

Even after that I got the error above. I tried to add all possible request methods to this CorsLayer but there were no success. I changed it to "Any" but nothing changed. Screenshot_20240618_012337

Here is my code:


    let cors = CorsLayer::new()
        .allow_methods(Any)
        .allow_headers(Any)
        .allow_origin(Any);
                // .allow_methods([Method::GET, Method::POST, Method::HEAD, Method::PUT, Method::DELETE, Method::PATCH])
                // .allow_headers(vec![http::header::CONTENT_TYPE])
                // .allow_origin("http://localhost:5173".parse::<HeaderValue>().unwrap()),

    let routes_all = Router::new()
        .merge(routes_login::routes(mm.clone()))
        .nest("/api", routes_rpc)
        .nest("/f", route_fstg)
        .nest("/d", route_dstg)
        .layer(middleware::map_response(mw_reponse_map))
        .layer(middleware::from_fn_with_state(
            app_auth_state.clone(),
            mw_ctx_resolve,
        ))
        .layer(middleware::from_fn(mw_req_stamp))
        .layer(CookieManagerLayer::new())
        .fallback_service(routes_static::serve_dir())
        .layer(cors);

Please let me know if I'm doing something wrong.

jplatte commented 2 months ago

The cors middleware never returns method-not-allowed. It also doesn't set the Allow header (what it does set is the Access-Control-Request-Method header).

It sounds like you are having problems with the axum routing setup. Please use axum's Q&A section, and post your full routing setup.