Use wasm-bindgen to Call fetch() from Rust

In this Shortcut, you are going to expand on what you have learned so far, by using wasm-bindgen to call the Fetch API from Rust. This is a standard API available in the browser that allows you to make modern HTTP calls from your JavaScript code. As you saw in “Use wasm-bindgen to Modify the DOM from Rust,” wasm-bindgen makes it easy to invoke browser behavior, so being able to do this now should not be terribly surprising. This is significant, however, because your WebAssembly code by default cannot directly access the network.

In the GitHub repository for this Shortcut, you should enter the directory 15-Fetch. The readme.md file contains installation instructions and a description of the state of the project. I have initialized the fetch_from_browser project with the Rust cargo functionality and added the wasm-bindgen, wasm-bindgen-futures, and js-sys dependencies to the Cargo.toml file. As you will recall from the previously mentioned Shortcut, we also rely on Cargo features to trigger the scaffolding code we need access to from our browser environment, so those dependencies are listed in this file as well.

Install any dependencies needed:

> npm install

The index.html has two notable elements:

<html> <head> <meta content="text/html;charset=utf-8" http-equiv="Content-Type"/> </head> <body> <p>By the time this loads, you should see something below...</p> <img style="height: ...

Get Use wasm-bindgen to Call fetch() from Rust now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.