Module actix_web::middleware::cors
source · Expand description
Cross-origin resource sharing (CORS) for Actix applications
CORS middleware could be used with application and with resource. First you need to construct CORS middleware instance.
To construct a cors:
- Call
Cors::build
to start building. - Use any of the builder methods to set fields in the backend.
- Call finish to retrieve the constructed backend.
Cors middleware could be used as parameter for App::middleware()
or
Resource::middleware()
methods. But you have to use
Cors::for_app()
method to support preflight OPTIONS request.
Example
use actix_web::middleware::cors::Cors;
use actix_web::{http, App, HttpRequest, HttpResponse};
fn index(mut req: HttpRequest) -> &'static str {
"Hello world"
}
fn main() {
let app = App::new().configure(|app| {
Cors::for_app(app) // <- Construct CORS middleware builder
.allowed_origin("https://www.rust-lang.org/")
.allowed_methods(vec!["GET", "POST"])
.allowed_headers(vec![http::header::AUTHORIZATION, http::header::ACCEPT])
.allowed_header(http::header::CONTENT_TYPE)
.max_age(3600)
.resource("/index.html", |r| {
r.method(http::Method::GET).f(|_| HttpResponse::Ok());
r.method(http::Method::HEAD).f(|_| HttpResponse::MethodNotAllowed());
})
.register()
});
}
In this example custom CORS middleware get registered for “/index.html” endpoint.
Cors middleware automatically handle OPTIONS preflight request.
Structs
Middleware
for Cross-origin resource sharing supportStructure that follows the builder pattern for building
Cors
middleware
structs.