#Passing axum State/Json to dioxus server calls

1 messages · Page 1 of 1 (latest)

lunar quarry
#

I am trying to pass a state defined in axum to dioxus functions marked with #[server].
I have many issues.

First of all, the project doesn't detect Json. I have the feature server enabled:

[features]
default = []
web = ["dioxus/web"]
desktop = ["dioxus/desktop"]
mobile = ["dioxus/mobile"]
server = ["dioxus/server", "dep:rusqlite", "dep:axum", "dep:tokio"]

Every time I run dx serve --platform server I get a called Result::unwrap()on anErr value: Os { code: 48, kind: AddrInUse, message: "Address already in use" }.
I assume because the dx serve spins up a server that is listening on the same port as my server 8080.
This is the launch_server:

#[cfg(feature = "server")]
async fn launch_server() {
    use axum::routing::post;

    dioxus::logger::initialize_default();

    let state = server::AppState { ... };

    let router = axum::Router::new()
        .serve_dioxus_application(ServeConfigBuilder::new(), App)
        .route("/vote", post(server::perform_vote))
        .with_state(state)
        .into_make_service();

    let listener = tokio::net::TcpListener::bind("0.0.0.0:8080").await.unwrap();
    tracing::info!("Started listening on {}", listener.local_addr().unwrap());
    axum::serve(listener, router).await.unwrap();
}

Second of all, in the perform_vote function, I cannot use extract::Json with the #[server] macro. When building the project the function fails with many errors like

12:06:18 [cargo] error: expected `:`, found `(`
  --> src/main.rs:96:31
   |
96 | pub async fn perform_vote(Json(vote): Vote<VoteReq>) -> Result<(), ServerFnError> {
   |              ------------     ^^^^^^ expected `:`

I ended up defining the function in the backend like this:

pub async fn perform_vote(
    State(state): State<AppState>,
    Json(vote): Json<VoteReq>,
) -> Result<(), (StatusCode, String)> {

(i'll continue on the first comment)

#

But I don't seem to be able to call it from the frontend. Notice that when I defined the Router I specified a route for the /vote endpoint.

let router = axum::Router::new()
        .serve_dioxus_application(ServeConfigBuilder::new(), App)
        .route("/vote", post(server::perform_vote))
        .with_state(state)
        .into_make_service();

In the frontend (yes, the port 3000 is correct, I tried already):

client.post("http://localhost:3000/vote")
#

Also, what is the difference between building with web and server in this case? Should I just build with server?

lunar quarry
#

I see that using

LaunchBuilder::new()
        .with_context(...)

works, but then why would I use axum in this case? I also want to run some async before LaunchBuilder, is that possible?

#

Indeed, using something like LaunchBuilder works, but that means that axum is not very much compatible then with dioxus

analog kestrel
#

The CLI will try to proxy your server function app with devtools so you can't serve it on the same port