CORS

CORS 中間件可以用於 跨源資源共享在新窗口打開.

由於瀏覽器會發 Method::OPTIONS 的請求, 所以需要增加對此類請求的處理, 有兩種方式可以處理 OPTIONS 的請求.

  • 可以對根 Router 添加 empty_handler
Router::with_hoop(cors).get(hello).options(handler::empty());
  • 可以在 Catcher 上添加 cors 的 Handler:
let cors = Cors::new()
        .allow_origin(["http://127.0.0.1:5800", "http://localhost:5800"])
        .allow_methods(vec![Method::GET, Method::POST, Method::DELETE])
        .allow_headers("authorization")
        .into_handler();
let acceptor = TcpListener::new("0.0.0.0:5600").bind().await;
let service = Service::new(router).catcher(Catcher::default().hoop(cors));
Server::new(acceptor).serve(service).await;

示例代碼

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"