mirror of
https://github.com/tokio-rs/axum.git
synced 2026-08-27 00:00:24 +02:00
Add CORS example (#512)
This commit is contained in:
@@ -0,0 +1,10 @@
|
|||||||
|
[package]
|
||||||
|
name = "example-cors"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2018"
|
||||||
|
publish = false
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
axum = { path = "../../axum" }
|
||||||
|
tokio = { version = "1.0", features = ["full"] }
|
||||||
|
tower-http = { version = "0.1", features = ["cors"] }
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
//! Run with
|
||||||
|
//!
|
||||||
|
//! ```not_rust
|
||||||
|
//! cargo run -p example-cors
|
||||||
|
//! ```
|
||||||
|
|
||||||
|
use axum::{
|
||||||
|
http::Method,
|
||||||
|
response::{Html, IntoResponse},
|
||||||
|
routing::get,
|
||||||
|
Json, Router,
|
||||||
|
};
|
||||||
|
use std::net::SocketAddr;
|
||||||
|
use tower_http::cors::{CorsLayer, Origin};
|
||||||
|
|
||||||
|
#[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
|
||||||
|
CorsLayer::new()
|
||||||
|
.allow_origin(Origin::exact("http://localhost:3000".parse().unwrap()))
|
||||||
|
.allow_methods(vec![Method::GET]),
|
||||||
|
);
|
||||||
|
serve(app, 4000).await;
|
||||||
|
};
|
||||||
|
|
||||||
|
tokio::join!(frontend, backend);
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn serve(app: Router, port: u16) {
|
||||||
|
let addr = SocketAddr::from(([127, 0, 0, 1], port));
|
||||||
|
axum::Server::bind(&addr)
|
||||||
|
.serve(app.into_make_service())
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
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"])
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user