CORS 跨域 #
什么是 CORS? #
跨域资源共享(CORS)是一种机制,允许服务器指示哪些来源可以访问其资源。
添加依赖 #
toml
[dependencies]
actix-cors = "0.6"
基本配置 #
允许所有来源 #
rust
use actix_cors::Cors;
use actix_web::{web, App, HttpServer};
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.wrap(Cors::permissive())
})
.bind("127.0.0.1:8080")?
.run()
.await
}
指定来源 #
rust
use actix_web::http::header;
App::new()
.wrap(
Cors::default()
.allowed_origin("https://example.com")
.allowed_origin("http://localhost:3000")
.allowed_methods(vec!["GET", "POST", "PUT", "DELETE"])
.allowed_headers(vec![header::AUTHORIZATION, header::ACCEPT])
.allowed_header(header::CONTENT_TYPE)
.max_age(3600)
)
动态来源 #
rust
App::new()
.wrap(
Cors::default()
.allowed_origin_fn(|origin, _req| {
origin.as_bytes().ends_with(b".example.com")
})
)
完整配置 #
rust
use actix_cors::Cors;
use actix_web::{http::header, web, App, HttpServer, HttpResponse, Responder};
async fn index() -> impl Responder {
HttpResponse::Ok().json(serde_json::json!({ "message": "Hello" }))
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.wrap(
Cors::default()
.allowed_origin("http://localhost:3000")
.allowed_methods(vec!["GET", "POST", "PUT", "DELETE"])
.allowed_headers(vec![
header::AUTHORIZATION,
header::ACCEPT,
header::CONTENT_TYPE,
])
.expose_headers(vec![header::CONTENT_DISPOSITION])
.supports_credentials()
.max_age(3600)
)
.route("/", web::get().to(index))
})
.bind("127.0.0.1:8080")?
.run()
.await
}
下一步 #
继续学习 安全最佳实践,了解安全配置!
最后更新:2026-03-29