'Access-Control-Allow-Origin' missing using actix-web

Stuck on this problem where I received this error everytime making POST request to my actix-web server.

CORS header 'Access-Control-Allow-Origin' missing

The post from here is not solving the problem.

my javascript (VueJs running on localhost:3000) :

let data = //some json data
let xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:8080/abc");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onload = () => {
    console.log(xhr.responseText);
}
xhr.send(JSON.stringify(data));

My Actix_Web server (running on localhost:8080) :

#[actix_web::main]
async fn main() {

    HttpServer::new(move || {
        let cors = Cors::default()
        .allowed_origin("http://localhost:3000/")
        .allowed_methods(vec!["GET", "POST"])
        .allowed_header(actix_web::http::header::ACCEPT)
        .allowed_header(actix_web::http::header::CONTENT_TYPE)
        .max_age(3600);

        App::new()
        .wrap(cors)
        .service(myfunc)
    })
    .bind(("0.0.0.0", 8080))
    .unwrap()
    .run()
    .await
    .unwrap();
}

my cargo.toml dependencies

[dependencies]
actix-web = "4"
actix-cors = "0.6.1"
...

Got any idea?

The XMLHttpRequest API does not add CORS request headers automatically. I'd recommend migrating to the Fetch API and enabling CORS mode on that. See this MDN page.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.