Skip to content

Commit

Permalink
Add NodeJS support. Fixes #31 (#58)
Browse files Browse the repository at this point in the history
Fixes #31.

Use a direct binding of fetch that is now available in NodeJS >= v18.0
  • Loading branch information
lvauvillier authored Sep 2, 2024
1 parent 4e63d73 commit 476b5c3
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 3 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
![MIT](https://img.shields.io/badge/license-MIT-blue.svg)
![Apache](https://img.shields.io/badge/license-Apache-blue.svg)

If you want to do HTTP requests and are targeting both native and web (WASM), then this is the crate for you!
If you want to do HTTP requests and are targeting both native, web (WASM) and NodeJS (since v18.0), then this is the crate for you!

[You can try the web demo here](https://emilk.github.io/ehttp/index.html) (works in any browser with WASM and WebGL support). Uses [`eframe`](https://github.com/emilk/egui/tree/master/crates/eframe).

Expand Down
10 changes: 8 additions & 2 deletions ehttp/src/web.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,13 @@ use wasm_bindgen_futures::JsFuture;
use crate::types::PartialResponse;
use crate::{Request, Response};

/// Binds the JavaScript `fetch` method for use in both Node.js (>= v18.0) and browser environments.
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(js_name = fetch)]
fn fetch_with_request(input: &web_sys::Request) -> js_sys::Promise;
}

/// Only available when compiling for web.
///
/// NOTE: `Ok(…)` is returned on network error.
Expand Down Expand Up @@ -57,8 +64,7 @@ pub(crate) async fn fetch_base(request: &Request) -> Result<web_sys::Response, J
js_request.headers().set(k, v)?;
}

let window = web_sys::window().unwrap();
let response = JsFuture::from(window.fetch_with_request(&js_request)).await?;
let response = JsFuture::from(fetch_with_request(&js_request)).await?;
let response: web_sys::Response = response.dyn_into()?;

Ok(response)
Expand Down

0 comments on commit 476b5c3

Please sign in to comment.