Adding Cors to the API server so I can enable live view on the Angular view
I needed to add Cors support so I could do live dev on the Angular components. Basically I didn’t want to rebuild the rust every time I made a tweak to the layout. I achieved this by addin in the rocker_cors crate:
Basically after adding in the crate you need to create the Cors config object and then use it like middleware in node or flask - as a chained operation on the request :
//copied from the blog above
fn make_cors() -> Cors {
// Set up the origins allowed - In my case I wanted this for
// the ng serve (But I was also working on WSL2 so it was forwarded
// by vscode) so I needed the origins for 4200/4201
let allowed_origins = AllowedOrigins::some_exact(&[
"http://localhost:8080",
"http://127.0.0.1:8080",
"http://localhost:8000",
"http://0.0.0.0:8000",
]);
//Now we can set up
CorsOptions {
allowed_origins,
allowed_methods: vec![Method::Get].into_iter().map(From::from).collect(),
allowed_headers: AllowedHeaders::some(&[
"Authorization",
"Accept",
"Access-Control-Allow-Origin", // 6.
]),
allow_credentials: true,
..Default::default()
}
.to_cors()
.expect("error while building CORS")
}
// In my main function I added in the above fn
rocket::ignite()
.mount("/api", routes![get_tasks, add_task, get_task_by_id])
.mount("/", StaticFiles::from("view/dist"))
.attach(make_cors()) //Add in Cors handling...
.manage(task_db)
.launch();
The attach
method attaches a type that has the Fairing
Trait. This is Rockets approach to structured middleware which allows the modification of the request during it’s lifetime.