emilk / ehttp

Minimal Rust HTTP client for both native and WASM

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Support for nodejs

robrennie opened this issue · comments

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!

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

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: rustwasm/wasm-pack#795 (comment)

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.

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.

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

@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!

@robrennie I made the PR