CORS

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

由于浏览器会发 Method::OPTIONS 的请求, 所以需要增加对此类请求的处理, 需要吧中间件添加到 Service 上.

示例代码

use salvo::cors::Cors;
use salvo::http::Method;
use salvo::prelude::*;

#[handler]
async fn hello() -> &'static str {
    "hello"
}

#[tokio::main]
async fn main() {
    tracing_subscriber::fmt().init();

    let cors = Cors::new()
        .allow_origin("https://salvo.rs")
        .allow_methods(vec![Method::GET, Method::POST, Method::DELETE])
        .into_handler();

    let router = Router::new().get(hello);
    let service = Service::new(router).hoop(cors);

    let acceptor = TcpListener::new("127.0.0.1:5800").bind().await;
    Server::new(acceptor).serve(service).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"