The fetch API

The fetch API is widely used in browser and node-based JavaScript applications to fetch content over the network. Building on top of its non-blocking aysnc network socket API, the WasmEdge QuickJS runtime supports the fetch API. That makes a lot of JS APIs and modules reusable out of the box.

The example_js/wasi_http_fetch.js example demonstrates how to use the fetch API in WasmEdge. The code snippet below shows an async HTTP GET. While the program waits for and processes the GET content, it can start another request.

  1. import { fetch } from 'http'
  2. async function test_fetch() {
  3. try {
  4. let r = await fetch("http://152.136.235.225/get?id=1")
  5. print('test_fetch\n', await r.text())
  6. } catch (e) {
  7. print(e)
  8. }
  9. }
  10. test_fetch()

The code snippet below shows how to do an sync HTTP POST to a remote server.

  1. async function test_fetch_post() {
  2. try {
  3. let r = await fetch("http://152.136.235.225/post", { method: 'post', 'body': 'post_body' })
  4. print('test_fetch_post\n', await r.text())
  5. } catch (e) {
  6. print(e)
  7. }
  8. }
  9. test_fetch_post()

An async HTTP PUT request is as follows.

  1. async function test_fetch_put() {
  2. try {
  3. let r = await fetch("http://152.136.235.225/put",
  4. {
  5. method: "put",
  6. body: JSON.stringify({ a: 1 }),
  7. headers: { 'Context-type': 'application/json' }
  8. })
  9. print('test_fetch_put\n', await r.text())
  10. } catch (e) {
  11. print(e)
  12. }
  13. }
  14. test_fetch_put()

To run those examples, use the following WasmEdge CLI command.

  1. cd example_js
  2. wasmedge --dir .:. ../target/wasm32-wasi/release/wasmedge_quickjs.wasm wasi_http_fetch.js

You can see the HTTP responses printed to the console.