emilk / ehttp

Minimal Rust HTTP client for both native and WASM
Apache License 2.0
316 stars 30 forks source link

Support for nodejs #31

Closed robrennie closed 2 weeks ago

robrennie commented 1 year ago

Perhaps I'm doing something wrong, but when I use wasm-pack with a --target of nodejs and then run in a simple node test script, it panics as shown below.

panicked at 'called Option::unwrap() on a None value', ...\ehttp-0.3.0\src\web.rs:37:36

It seems this points to code that is expecting it to be run in a browser. Any chance there may be a way to support node?

Thanks!

emilk commented 1 year ago

Yes, ehttp currently expects to run in a browser.

If you want node support, you'll have to build it :) It shouldn't be too hard - just remove the calls to web_sys::window() and replace the fetch_with_request with whatever the equivalent is in nodejs

robrennie commented 1 year ago

Yes, I could write it, but I figured I'd ask you to write it first :)

The hard part isn't the code, it's detecting what wasm-pack is targeting from within Rust: https://github.com/rustwasm/wasm-pack/issues/795#issue-568423906

lvauvillier commented 2 months ago

Hey @robrennie, @emilk, as Node.js now supports the fetch API (since v18.0), we can easily bypass the web_sys::window() + fetch_with_request call by directly mapping fetch as external function (this is what web_sys does internally).

This simple code does the trick:

#[wasm_bindgen]
extern "C" {
    #[wasm_bindgen(js_name = fetch)]
    fn fetch_with_request(input: &web_sys::Request) -> Promise;
} 

If I find some time in the coming days, I'll make a PR.

robrennie commented 2 months ago

Hi @lvauvillier - I think you'll still run into the conditional compilation problem with wasm-pack (see the comment above) where you can't access the --target parameter to tell whether you're targeting nodejs or web.

lvauvillier commented 2 months ago

The code is isomorphic, functioning seamlessly on both Node (since v18.0) and the browser. So, no conditional compilation is needed.

in browsers fetch === window.fetch

robrennie commented 2 months ago

@lvauvillier - well that's pretty great! Didn't realize - I'm more a Rustacean than a javascripter. Looking forward to a new version with this!

lvauvillier commented 2 months ago

@robrennie I made the PR