Caio Ishikawa
Caio Ishikawa

Reputation: 199

Blocked by CORS on Actix Web backend with Cors::permissive()

I'm trying to build out a simple backend with Rust, but I keep running into a CORS error.

My react frontend says:

Access to XMLHttpRequest at 'http://127.0.0.1:3002/auth' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Here's my backend code:

// Route Config //
pub fn routes(cfg: &mut web::ServiceConfig) { 
    cfg.route("/auth", web::get().to(auth_handler));
}

// Handler Config //
async fn auth_handler() -> impl Responder { 
    HttpResponse::Ok().json("Works")
}

#[actix_rt::main]
async fn main() -> io::Result<()> { 
    let app = move || App::new().configure(routes);
    let _cors = Cors::permissive();
    HttpServer::new(app).bind("127.0.0.1:3002")?.run().await
}

To my understanding, the CORS::permissive() function should allow all cross site interactions to work. Did I misunderstand the docs, or did I implement it wrong?

Upvotes: 4

Views: 2001

Answers (2)

Ragy Abraham
Ragy Abraham

Reputation: 86

Another option is to use the actix_cors crate which has been created to specifically handle this use case.

So the main function would look something like this:

use actix_cors::Cors;
use actix_web::{http::header, App, HttpServer};

#[actix_web::main]
async fn main() -> std::io::Result<()> {

    HttpServer::new(move || {
        App::new()
            .wrap(
                Cors::default()
                    .allowed_origin("*")
                    .allowed_methods(vec!["GET", "POST"])
                    .allowed_headers(vec![header::AUTHORIZATION, header::ACCEPT])
                    .allowed_header(header::CONTENT_TYPE),
            )
            .wrap(Logger::default())
            .service(user::info)
    })
    .bind(("127.0.0.1", 3002))?
    .run()
    .await
}

Upvotes: 0

kmdreko
kmdreko

Reputation: 60272

You need to actually use the Cors middleware in your App via .wrap():

let app = move || App::new().wrap(Cors::permissive()).configure(routes);
                         // ^^^^^^^^^^^^^^^^^^^^^^^^^

More info on configuring it here.

Upvotes: 5

Related Questions