CORS

CORS 中间件可以用于 跨域资源共享在新窗口打开.

由于浏览器会发 Method::OPTIONS 的请求, 所以需要增加对此类请求的处理. 可以对根 Router 添加 empty_handler 一劳永逸地处理这种情况.

配置 Cargo.toml

salvo = { version = "*", features = ["cors"] }

示例代码

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(empty_handler);

    let acceptor = TcpListener::new("127.0.0.1:7878").bind().await;
    Server::new(acceptor).serve(router).await;
}
[package]
name = "example-cors"
version = "0.1.0"
edition = "2021"
publish = false


[dependencies]
salvo = { git = "https://github.com/salvo-rs/salvo.git", features=["cors"] }
tokio = { version = "1", features = ["macros"] }
tracing = "0.1"
tracing-subscriber = "0.3"