CORS POST XHR or Fetch request don't work with Actix Rust HTTP server

Viewed 269

Could you please help me fix this issue with XHR/Fetch queries in the browser that are not working with my Actix back-end server?

I tested it with Postman, it is working okay but I still get the CORS error though I added the "Access-Control-Allow-Origin", "*" to the response.

Thank you.

Back-end

#[derive(Deserialize)]
struct URL{
    t : String, 
    c : i32,
    a : String
}

#[post("/get")]
async fn get_data(query: web::Json<URL>) -> impl Responder{
    println!("Got a form data query");
    HttpResponse::Ok().header("Access-Control-Allow-Origin", "*").body(String::from("Success msg from server"))
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .service(get_data)
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

Front-end query:

fetch("http://127.0.0.1:8080/get", {
    method: 'POST',
    mode: 'no-cors',
    cache: 'no-cache',
    body: JSON.stringify({
    "t":"some data",
    "a":"an example",
    "c":0
})
  });

The front-end is running on http://127.0.0.1:7500.

1 Answers

You have to handle CORS on the Server side. You need to install the actix-cors-0.5.x library and import it into file. In your code you could handle it this way (development code only):

App::new()
   .wrap(Cors::permissive())
   .service(get_data)

See answer here

Related