如何在 WASM-Bindgen 和 Rust 中实际获取响应主体的文本

How to actually get the text of the response body in WASM-Bindgen and Rust

也许这是一个简单的问题,但我还没有找到答案。我已经搜索了文档,但我在整个互联网上找到的单个 web-sys fetch 示例仍然没有解决这个问题(官方文档,不少)。

如何从 web-sys 请求中获取响应主体?它具有 JsFutures 和解包的所有这些开销,我实际上似乎无法找到正确的方法来将我的数据放入字符串中。我只是想从(localhost dev)服务器检索一个文件,然后将其解析为 WebGL 程序的顶点着色器,但我什至无法获取它的字符串或以任何方式读取它。

Response 类型上有一个 body 方法,请参阅 https://rustwasm.github.io/wasm-bindgen/api/web_sys/struct.Response.html#method.body

还有一个 text 方法,returns 一个 Promise 将解析为 JsValue

https://rustwasm.github.io/wasm-bindgen/examples/fetch.html

为例

你应该可以这样做:

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();