-
I used salvo cors with socket,but i always get cors error. use salvo::catcher::Catcher;
use salvo::cors::{self, Cors};
use salvo::http::Method;
use salvo::prelude::*;
use serde_json::Value;
use socketioxide::{
extract::{AckSender, Bin, Data, SocketRef},
SocketIo,
};
use tracing::info;
use tracing_subscriber::FmtSubscriber;
fn on_connect(socket: SocketRef, Data(data): Data<Value>) {
info!("Socket.IO connected: {:?} {:?}", socket.ns(), socket.id);
socket.emit("auth", data).ok();
socket.on(
"message",
|socket: SocketRef, Data::<Value>(data), Bin(bin)| {
info!("Received event: {:?} {:?}", data, bin);
socket.bin(bin).emit("message-back", data).ok();
},
);
socket.on(
"message-with-ack",
|Data::<Value>(data), ack: AckSender, Bin(bin)| {
info!("Received event: {:?} {:?}", data, bin);
ack.bin(bin).send(data).ok();
},
);
}
#[handler]
async fn hello() -> &'static str {
"Hello World"
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let subscriber = FmtSubscriber::new();
tracing::subscriber::set_global_default(subscriber)?;
// socket
let (layer, io) = SocketIo::new_layer();
io.ns("/", on_connect);
io.ns("/custom", on_connect);
let layer = layer.compat();
// cors
let cors_handler = Cors::new()
.allow_origin(cors::Any)
.allow_methods([Method::GET, Method::POST, Method::DELETE])
.into_handler();
let router = Router::with_hoop(cors_handler.clone())
.push(Router::with_path("/socket.io").hoop(layer).goal(hello));
// server
let acceptor = TcpListener::new("192.168.36.6:10008").bind().await;
let service = Service::new(router).catcher(Catcher::default().hoop(cors_handler));
Server::new(acceptor).serve(service).await;
Ok(())
} How should i do? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
The requests that are handled by socketioxide don't pass through the cors system of salvo. What you need to do is to use the |
Beta Was this translation helpful? Give feedback.
-
An example has been added to the // This code is used to integrates other tower layers before or after Socket.IO such as CORS
// Beware that classic salvo request won't pass through these layers
let layer = ServiceBuilder::new()
.layer(CorsLayer::permissive()) // Enable CORS policy
.layer(layer); // Mount Socket.IO |
Beta Was this translation helpful? Give feedback.
An example has been added to the
salvo-echo
example with PR #221 :