Search code examples
rustcorsrust-rocket

How fix CorsOptions for Rocket?


I found this code for configuring CORS using rocket_cors:

use rocket::http::Method;
use rocket_cors::{AllowedOrigins, CorsOptions};

let cors = CorsOptions::default()
    .allowed_origins(AllowedOrigins::all())
    .allowed_methods(
        vec![Method::Get, Method::Post, Method::Patch]
            .into_iter()
            .map(From::from)
            .collect(),
    )
    .allow_credentials(true);

rocket::build().attach(cors.to_cors())

but when I run the program I get an error:

error[E0277]: the trait bound `rocket_cors::Method: From<rocket::http::Method>` is not satisfied
  --> src/main.rs:37:13
   |
37 | /             vec![Method::Get, Method::Post, Method::Patch]
38 | |                 .into_iter()
39 | |                 .map(From::from)
40 | |                 .collect(),
   | |__________________________^ the trait `From<rocket::http::Method>` is not implemented for `rocket_cors::Method`
   |
   = help: the trait `From<rocket_http::method::Method>` is implemented for `rocket_cors::Method`

I don't know how fix this.


Solution

  • The latest published stable versions of the crate (< 0.5.1) are not compatible with the latest versions of rustc and rocket.

    You can use the development version of the crate using git + branch arguments in Cargo.toml.

    Cargo.toml

    [dependencies]
    rocket_cors = { git = "https://github.com/lawliet89/rocket_cors", branch = "master" }
    rocket = "0.5.0-rc.2"
    

    Additionally the documentation state to use the manage-function instead of attach-function.

    main.rs

    #[macro_use] extern crate rocket;
    
    use rocket::{Build, Rocket};
    use rocket::http::Method;
    use rocket_cors::{AllowedOrigins, CorsOptions};
    
    #[launch]
    fn rocket() -> Rocket<Build> {
        let cors = CorsOptions::default()
            .allowed_origins(AllowedOrigins::all())
            .allowed_methods(
                vec![Method::Get, Method::Post, Method::Patch]
                    .into_iter()
                    .map(From::from)
                    .collect(),
            )
            .allow_credentials(true);
        rocket::build().manage(cors.to_cors())
    }