Files
axum/examples/cors/src/main.rs
T

62 lines
1.7 KiB
Rust
Raw Normal View History

2021-11-13 22:18:14 +01:00
//! Run with
//!
//! ```not_rust
//! cargo run -p example-cors
2021-11-13 22:18:14 +01:00
//! ```
use axum::{
2022-04-25 16:59:16 +02:00
http::{HeaderValue, Method},
2021-11-13 22:18:14 +01:00
response::{Html, IntoResponse},
routing::get,
Json, Router,
};
use std::net::SocketAddr;
2022-04-25 16:59:16 +02:00
use tower_http::cors::CorsLayer;
2021-11-13 22:18:14 +01:00
#[tokio::main]
async fn main() {
let frontend = async {
let app = Router::new().route("/", get(html));
serve(app, 3000).await;
};
let backend = async {
let app = Router::new().route("/json", get(json)).layer(
// see https://docs.rs/tower-http/latest/tower_http/cors/index.html
// for more details
2022-04-17 11:13:22 +03:00
//
// pay attention that for some request types like posting content-type: application/json
2022-05-12 11:36:57 +02:00
// it is required to add ".allow_headers([http::header::CONTENT_TYPE])"
2022-04-17 11:13:22 +03:00
// or see this issue https://github.com/tokio-rs/axum/issues/849
2021-11-13 22:18:14 +01:00
CorsLayer::new()
2022-04-25 16:59:16 +02:00
.allow_origin("http://localhost:3000".parse::<HeaderValue>().unwrap())
2022-05-12 11:36:57 +02:00
.allow_methods([Method::GET]),
2021-11-13 22:18:14 +01:00
);
serve(app, 4000).await;
};
tokio::join!(frontend, backend);
}
async fn serve(app: Router, port: u16) {
let addr = SocketAddr::from(([127, 0, 0, 1], port));
let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
2025-12-28 09:25:50 +01:00
axum::serve(listener, app).await;
2021-11-13 22:18:14 +01:00
}
async fn html() -> impl IntoResponse {
Html(
r#"
<script>
fetch('http://localhost:4000/json')
.then(response => response.json())
.then(data => console.log(data));
</script>
"#,
)
}
async fn json() -> impl IntoResponse {
Json(vec!["one", "two", "three"])
}