diff --git a/desktop/crates/test-http-api/src/api.rs b/desktop/crates/test-http-api/src/api.rs index f8c90668c..bbfe3689f 100644 --- a/desktop/crates/test-http-api/src/api.rs +++ b/desktop/crates/test-http-api/src/api.rs @@ -297,6 +297,7 @@ pub fn router(shared: Shared) -> Router { .route("/notification_count", post(notification_count_handler)) .merge(writes) .layer(middleware::from_fn(read_body)) + .layer(middleware::from_fn(plain_text_is_json)) .layer( CorsLayer::new() .allow_origin(cors::AllowOrigin::list( @@ -321,6 +322,22 @@ async fn read_body(request: Request, next: Next) -> Response { } } +/// The app sends JSON as `text/plain` so the browser skips the CORS +/// preflight; `Json` only accepts `application/json`. +async fn plain_text_is_json(mut request: Request, next: Next) -> Response { + let plain = request + .headers() + .get(CONTENT_TYPE) + .and_then(|value| value.to_str().ok()) + .is_some_and(|value| value.starts_with("text/plain")); + if plain { + request + .headers_mut() + .insert(CONTENT_TYPE, HeaderValue::from_static("application/json")); + } + next.run(request).await +} + async fn serialize_writes( State(lock): State>>, request: Request, diff --git a/desktop/src/lib/invoke.ts b/desktop/src/lib/invoke.ts index d5751087b..6cc9d4bbf 100644 --- a/desktop/src/lib/invoke.ts +++ b/desktop/src/lib/invoke.ts @@ -97,9 +97,11 @@ async function withTestBackend( } else { const raw = args instanceof Uint8Array; const headers = new Headers(options?.headers); + // `text/plain` keeps JSON calls CORS-simple, so WebKit sends no preflight. + // Its connection churn around preflights loses requests at startup. headers.set( "Content-Type", - raw ? "application/octet-stream" : "application/json", + raw ? "application/octet-stream" : "text/plain;charset=UTF-8", ); return fetch(`http://127.0.0.1:${testHttpApiPort()}/${cmd}`, { method: "POST",