5

Maybe this is a simple question, but I have yet to find the answer anywhere. I've searched the documentation, but the single example I have found on the entire internet for web-sys fetch still doesn't address this (the official docs, no less).

How do you get the response body from a web-sys Request? It has all this overhead of JsFutures and unwrapping and I can't actually seem to find the correct way to get the thing to just put my data into a string. I'm just trying to retrieve a file from a (localhost dev) server and then parse it as the Vertex shader for a WebGL program, but I can't even get a string of it or read from it in any manner.

gajbooks
  • 65
  • 4

1 Answers1

4

There is a body method on the Response type see https://rustwasm.github.io/wasm-bindgen/api/web_sys/struct.Response.html#method.body

There is also a text method that returns a Promise that will resolve into a JsValue

Taking the example from https://rustwasm.github.io/wasm-bindgen/examples/fetch.html

You should be able to do something like this:

let mut opts = RequestInit::new();
opts.method("GET");
opts.mode(RequestMode::Cors);

let request = Request::new_with_str_and_init(
    "https://api.github.com/repos/rustwasm/wasm-bindgen/branches/master",
    &opts,
)?;

request
    .headers()
    .set("Accept", "application/vnd.github.v3+json")?;

let window = web_sys::window().unwrap();
let resp_value = JsFuture::from(window.fetch_with_request(&request)).await?;

// `resp_value` is a `Response` object.
assert!(resp_value.is_instance_of::<Response>());
let resp: Response = resp_value.dyn_into().unwrap();

// Convert this other `Promise` into a rust `Future`.
let text = JsFuture::from(resp.text()?).await?.as_string().unwrap();
Ömer Erden
  • 7,680
  • 5
  • 36
  • 45
izissise
  • 898
  • 1
  • 7
  • 23
  • 1
    That works great, thanks! JsValues can be converted to strings, but only after awaiting and then unwrapping. I think that was the mistake I was making. To me it seems like a lot of boilerplate code for a library that is ostensibly to help JS interoperability, but given the asynchronous nature of Javascript, maybe it is intended. – gajbooks Jan 17 '20 at 17:24
  • 1
    Maybe you can be interested in using stdweb https://github.com/koute/stdweb Which have more idiomatic rust usage – izissise Jan 18 '20 at 20:35
  • Perhaps check `resp.ok()` to make sure that it's not a 404 or missing auth. – neoneye Dec 31 '21 at 15:10