Configure CORS
This commit is contained in:
parent
e5d0219df8
commit
44c9f0e705
4 changed files with 32 additions and 7 deletions
|
|
@ -3,6 +3,7 @@ use std::env;
|
|||
#[derive(Clone)]
|
||||
pub struct Env {
|
||||
pub postgres_connection_string: String,
|
||||
pub allowed_origins: Vec<String>,
|
||||
}
|
||||
|
||||
impl Env {
|
||||
|
|
@ -10,8 +11,15 @@ impl Env {
|
|||
let postgres_connection_string = env::var("POSTGRES_CONNECTION_STRING")
|
||||
.expect("Missing POSTGRES_CONNECTION_STRING as an environment variable");
|
||||
|
||||
let allowed_origins = env::var("ALLOWED_ORIGINS")
|
||||
.expect("Missing ALLOWED_ORIGINS as an environment variable")
|
||||
.split(',')
|
||||
.map(|s| s.trim().to_string())
|
||||
.collect();
|
||||
|
||||
Env {
|
||||
postgres_connection_string,
|
||||
allowed_origins,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
18
src/lib.rs
18
src/lib.rs
|
|
@ -5,9 +5,25 @@ pub mod test_helpers;
|
|||
pub mod votes;
|
||||
|
||||
use axum::Router;
|
||||
use axum::http::{HeaderValue, Method, header};
|
||||
use state::AppState;
|
||||
use tower_http::cors::CorsLayer;
|
||||
use tower_http::trace::TraceLayer;
|
||||
|
||||
pub fn app(state: AppState) -> Router {
|
||||
routes::router(state).layer(TraceLayer::new_for_http())
|
||||
let origins: Vec<HeaderValue> = state
|
||||
.env
|
||||
.allowed_origins
|
||||
.iter()
|
||||
.map(|o| o.parse().expect("Invalid origin in ALLOWED_ORIGINS"))
|
||||
.collect();
|
||||
let cors = CorsLayer::new()
|
||||
.allow_origin(origins)
|
||||
.allow_methods([Method::GET, Method::POST, Method::DELETE])
|
||||
.allow_headers([header::CONTENT_TYPE])
|
||||
.allow_credentials(true);
|
||||
|
||||
routes::router(state)
|
||||
.layer(TraceLayer::new_for_http())
|
||||
.layer(cors)
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue