CORS
CORS middleware can be used for Cross-Origin Resource Sharing.
Since the browser will send Method::OPTIONS
requests, it is necessary to increase the handling of such requests. You can add empty_handler
to the root Router
to handle this situation once and for all.
Config Cargo.toml
salvo = { version = "*", features = ["cors"] }
Sample Code
use salvo::cors::Cors;
use salvo::prelude::*;
#[handler]
async fn hello() -> &'static str {
"hello"
}
#[tokio::main]
async fn main() {
tracing_subscriber::fmt().init();
let cors_handler = Cors::builder()
.allow_origin("https://salvo.rs")
.allow_methods(vec!["GET", "POST", "DELETE"])
.build();
let router = Router::with_hoop(cors_handler)
.get(hello)
.options(handler::empty());
let acceptor = TcpListener::new("127.0.0.1:5800").bind().await;
Server::new(acceptor).serve(router).await;
}
[package]
name = "example-cors"
version = "0.1.0"
edition = "2021"
publish = false
[dependencies]
salvo = { workspace = true, features=["cors"] }
tokio = { version = "1", features = ["macros"] }
tracing = "0.1"
tracing-subscriber = "0.3"