Search code examples
rustactix-web

How to add ACCESS_CONTROL_ALLOW_ORIGIN header in actix-web server?


Im trying to add a header to allow my API to be called from anywhere.

I try to use this (https://docs.rs/actix-web/latest/actix_web/http/header/constant.ACCESS_CONTROL_ALLOW_ORIGIN.html) with value * as the response header

I need that header for every request, so I think I need to wrap() it on App::new()

My cargo.toml:

actix-multipart = "0.4.0"
actix-web = "4.0.1"
actix-service = "2.0.2"
actix-rt = "2.2.0"

This code below doesn't work. Does anyone know how to do this ?

HttpServer::new(move || {
        let api_service = web::scope("/api")
            .configure(routes_provider)
            .route("/", web::get().to(|| HttpResponse::Ok()));

        App::new()
            .wrap(Logger::default())
            .wrap_fn(|req, srv| {
                let fut = srv.call(req);
                async {
                    let mut res = fut.await?;
                    res.headers_mut()
                        .insert(ACCESS_CONTROL_ALLOW_ORIGIN, HeaderValue::from_static("*"));
                    Ok(res)
                }
            })
            .service(api_service)
    })
    .bind(bind_addr)?
    .run()
    .await

Error from client-side (React - Axios) enter image description here


Solution

  • Have you tried to use the example from https://docs.rs/actix-cors/latest/actix_cors/ and with allow_any_origin?

    Applied to your code it might look something like:

    HttpServer::new(move || {
            let api_service = web::scope("/api")
                .configure(routes_provider)
                .route("/", web::get().to(|| HttpResponse::Ok()));
        
            let cors = Cors::default()
                  .allow_any_origin() // <--- this
                  .allowed_methods(vec!["GET", "POST"])
                  .allowed_headers(vec![http::header::AUTHORIZATION, http::header::ACCEPT])
                  .allowed_header(http::header::CONTENT_TYPE)
                  .max_age(3600);
    
            App::new()
                .wrap(cors)
                .wrap(Logger::default())
                .service(api_service)
        })
        .bind(bind_addr)?
        .run()
        .await