fetch API

檢視完整原始碼在線上檢視編譯後的範例

此範例使用 fetch API 向 GitHub API 發出 HTTP 請求,然後解析產生的 JSON。

Cargo.toml

Cargo.toml 啟用許多與 fetch API 和使用的類型相關的功能:HeadersRequest 等。

[package]
authors = ["The wasm-bindgen Developers"]
edition = "2021"
name = "fetch"
publish = false
version = "0.0.0"

[lib]
crate-type = ["cdylib"]

[dependencies]
js-sys = { path = "../../crates/js-sys" }
wasm-bindgen = { path = "../../" }
wasm-bindgen-futures = { path = "../../crates/futures" }

[dependencies.web-sys]
features = ['Headers', 'Request', 'RequestInit', 'RequestMode', 'Response', 'Window']
path = "../../crates/web-sys"

[lints]
workspace = true

src/lib.rs


# #![allow(unused_variables)]
#fn main() {
use wasm_bindgen::prelude::*;
use wasm_bindgen_futures::JsFuture;
use web_sys::{Request, RequestInit, RequestMode, Response};

#[wasm_bindgen]
pub async fn run(repo: String) -> Result<JsValue, JsValue> {
    let opts = RequestInit::new();
    opts.set_method("GET");
    opts.set_mode(RequestMode::Cors);

    let url = format!("https://api.github.com/repos/{}/branches/master", repo);

    let request = Request::new_with_str_and_init(&url, &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 json = JsFuture::from(resp.json()?).await?;

    // Send the JSON response back to JS.
    Ok(json)
}

#}