skip to Main Content

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;

2

Answers


  1. 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

    Login or Signup to reply.
  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]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search