如何添加CORS httpheader?
How to add CORS http header?
我正在尝试制作一个 Web 应用程序,前端使用 React,后端使用 Rust。我想我会通过 Tonic crate 使用 gRPC,在前端和后端之间进行通信。但我收到错误:
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.
关于如何使用 Tonic 添加 CORS header 有什么想法吗?
grpc-web 互操作性可以通过 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(())
}
见https://github.com/hyperium/tonic/pull/455 and https://docs.rs/tonic-web/latest/tonic_web/
我正在尝试制作一个 Web 应用程序,前端使用 React,后端使用 Rust。我想我会通过 Tonic crate 使用 gRPC,在前端和后端之间进行通信。但我收到错误:
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.
关于如何使用 Tonic 添加 CORS header 有什么想法吗?
grpc-web 互操作性可以通过 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(())
}
见https://github.com/hyperium/tonic/pull/455 and https://docs.rs/tonic-web/latest/tonic_web/