2

For a project I am using a rust back-end with the Axum framework. I am using react as a front-end. Atm, I just want to be able to make a simple request to the back-end. Everything works when I use a plug-in to disable CORS, but I don't get it working with CORS. What am I doing wrong? I am using a chrome browser.

code of the back-end:

async fn main() {
    // initialize tracing subscriber with console output
    tracing_subscriber::fmt()
        .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
        .init();

    let cors = CorsLayer::new()
        .allow_methods([Method::GET, Method::POST])
        .allow_origin(Any);

    // build our application with a single route
    let app = Router::new()
        .route("/", get(hello_world))
        .route("/", post(update_data))
        .layer(cors);

    // run it with hyper on localhost:3000
    axum::Server::bind(&"0.0.0.0:5000".parse().unwrap())
        .serve(app.into_make_service())
        .await
        .unwrap();
}

React front-end request:

import { Middleware } from 'redux';

const postMiddleware: Middleware = store => next => action => {
  const result = next(action);
  
  fetch('http://192.168.1.50:5000/', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': '*',
    },
    body: JSON.stringify({"title": "hello world!"})
  })
  .then(response => {
    console.log('Response:', response);
  })
  .catch(error => {
    console.error('Error:', error);
  });
    

  return result;
  
};

export default postMiddleware;
Bram Breda
  • 71
  • 7
  • 1
    Which error are you getting? Is it related to the "content-type"? Also, minor thing, in your request there is an `Access-Control-Allow-Origin` header, which is a not a request header, but a response one. IOW, it is doing nothing. – Eric Fortis Feb 28 '23 at 01:31
  • Drop that `Access-Control-Allow-Origin` header from your request: it's a _response_ header. Also, you'll need to allow the `Content-Type` header in your CORS configuration (on the server side): `.allow_headers("Content-Type")`; see https://docs.rs/tower-http/latest/tower_http/cors/struct.CorsLayer.html#method.allow_headers – jub0bs Feb 28 '23 at 07:15

2 Answers2

2

Try allow_headers "Content-Type"

use http::header::{CONTENT_TYPE};

let cors = CorsLayer::new()
   .allow_methods([Method::GET, Method::POST])
   .allow_origin(Any)
   .allow_headers([CONTENT_TYPE]);
Eric Fortis
  • 16,372
  • 6
  • 41
  • 62
0

Cors is going to be needed to be adjusted on the server side if you want to do it like that. I recommend going through your bundler of choice (vite or webpack, etc) and using their proxy instead (links go to the proxy docs). Generally in production you'll have a reverse proxy. if you do decide to do it (insecurely) server side then I'd recommend using tower_http

For reasons why it has to be done this was see here

Marcus Dunn
  • 487
  • 3
  • 7