diff --git a/backend/src/main.rs b/backend/src/main.rs index 01a189b..140bcc0 100644 --- a/backend/src/main.rs +++ b/backend/src/main.rs @@ -1,4 +1,9 @@ -use axum::{response::IntoResponse, routing::get, Json, Router}; +use axum::{ + http::{HeaderValue, Method}, + response::IntoResponse, + routing::get, + Json, Router, +}; use axum_extra::routing::SpaRouter; use clap::Parser; use serde::{Deserialize, Serialize}; @@ -6,6 +11,7 @@ use std::collections::HashMap; use std::net::{IpAddr, Ipv6Addr, SocketAddr}; use std::str::FromStr; use tower::ServiceBuilder; +use tower_http::cors::CorsLayer; use tower_http::trace::TraceLayer; #[derive(Deserialize, Serialize, Debug)] @@ -95,7 +101,18 @@ async fn main() { let app = Router::new() .route("/api/hello", get(hello)) .merge(SpaRouter::new("/assets", opt.static_dir)) - .layer(ServiceBuilder::new().layer(TraceLayer::new_for_http())); + .layer(ServiceBuilder::new().layer(TraceLayer::new_for_http())) + .layer( + // see https://docs.rs/tower-http/latest/tower_http/cors/index.html + // for more details + // + // pay attention that for some request types like posting content-type: application/json + // it is required to add ".allow_headers([http::header::CONTENT_TYPE])" + // or see this issue https://github.com/tokio-rs/axum/issues/849 + CorsLayer::new() + .allow_origin("http://localhost:8080".parse::().unwrap()) + .allow_methods([Method::GET]), + ); let sock_addr = SocketAddr::from(( IpAddr::from_str(opt.addr.as_str()).unwrap_or(IpAddr::V6(Ipv6Addr::LOCALHOST)),