Module cors

Expand description

Middleware which adds headers for CORS.

§Example

use std::convert::Infallible;
use bytes::Bytes;

use rama_http::{Body, Request, Response, Method, header};
use rama_http::layer::cors::{Any, CorsLayer};
use rama_core::service::service_fn;
use rama_core::{Context, Service, Layer};

async fn handle(request: Request) -> Result<Response, Infallible> {
    Ok(Response::new(Body::default()))
}

let cors = CorsLayer::new()
    // allow `GET` and `POST` when accessing the resource
    .allow_methods([Method::GET, Method::POST])
    // allow requests from any origin
    .allow_origin(Any);

let mut service = cors.into_layer(service_fn(handle));

let request = Request::builder()
    .header(header::ORIGIN, "https://example.com")
    .body(Body::default())
    .unwrap();

let response = service
    .serve(Context::default(), request)
    .await?;

assert_eq!(
    response.headers().get(header::ACCESS_CONTROL_ALLOW_ORIGIN).unwrap(),
    "*",
);

Structs§

AllowCredentials
Holds configuration for how to set the Access-Control-Allow-Credentials header.
AllowHeaders
Holds configuration for how to set the Access-Control-Allow-Headers header.
AllowMethods
Holds configuration for how to set the Access-Control-Allow-Methods header.
AllowOrigin
Holds configuration for how to set the Access-Control-Allow-Origin header.
AllowPrivateNetwork
Holds configuration for how to set the Access-Control-Allow-Private-Network header.
Any
Represents a wildcard value (*) used with some CORS headers such as CorsLayer::allow_methods.
Cors
Middleware which adds headers for CORS.
CorsLayer
Layer that applies the Cors middleware which adds headers for CORS.
ExposeHeaders
Holds configuration for how to set the Access-Control-Expose-Headers header.
MaxAge
Holds configuration for how to set the Access-Control-Max-Age header.
Vary
Holds configuration for how to set the Vary header.

Functions§

anyDeprecated
Represents a wildcard value (*) used with some CORS headers such as CorsLayer::allow_methods.
preflight_request_headers
Returns an iterator over the three request headers that may be involved in a CORS preflight request.