Home > Mobile >  How to add CORS http header?
How to add CORS http header?

Time:04-07

I'm trying to make a web app with React in the frontend and Rust as the backend. I thought I'd use gRPC through the Tonic crate, to communicate between the front and back end. But I'm getting the error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:50051/helloworld.Users/GetUsers. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 200.

Any ideas how I could add the CORS header with Tonic?

CodePudding user response:

grpc-web interoperability can be achieved through tonic-project crate tonic-web:

#[derive(Default)]
struct MyUsers;

#[tonic::async_trait]
impl UsersServer for MyUsers {
    // ...
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let my_service = MyUsers::default() // .. standard way to create tonic-service

    let service = tonic_web::config()
         .allow_origins(vec!["http://example.com"])
         .enable(UsersServerServer::new(my_service));
     
    Server::builder()
         .accept_http1(true)
         .add_service(service)
         .server("[::1]:50051".parse().unwrap()).await?;

    Ok(())
}

See https://github.com/hyperium/tonic/pull/455 and https://docs.rs/tonic-web/latest/tonic_web/

  • Related