Crate ntex_cors

source ·
Expand description

Cross-origin resource sharing (CORS) for ntex applications

CORS middleware could be used with application and with resource. Cors middleware could be used as parameter for App::wrap(), Resource::wrap() or Scope::wrap() methods.

§Example

use ntex_cors::Cors;
use ntex::{http, web};
use ntex::web::{App, HttpRequest, HttpResponse};

async fn index(req: HttpRequest) -> &'static str {
    "Hello world"
}

#[ntex::main]
async fn main() -> std::io::Result<()> {
    web::server(|| App::new()
        .wrap(
            Cors::new() // <- 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)
              .finish())
        .service(
            web::resource("/index.html")
              .route(web::get().to(index))
              .route(web::head().to(|| async { HttpResponse::MethodNotAllowed() }))
        ))
        .bind("127.0.0.1:8080")?
        .run()
        .await
}

In this example custom CORS middleware get registered for “/index.html” endpoint.

Cors middleware automatically handle OPTIONS preflight request.

Structs§

  • Structure that follows the builder pattern for building Cors middleware structs.
  • Middleware for Cross-origin resource sharing support
  • Middleware for Cross-origin resource sharing support

Enums§

  • An enum signifying that some of type T is allowed, or All (everything is allowed).
  • A set of errors that can occur during processing CORS