HTTP Request from inside WASM using emscripten_fetch() and callbacks

This example uses emscripten_fetch() with onsuccess and onerror callbacks.

See the output in browser developer console.

Actual code:


void requestOnSuccess(emscripten_fetch_t *fetch)
{
    char dat[fetch->numBytes + 1];
    memcpy(dat, fetch->data, fetch->numBytes);
    dat[fetch->numBytes] = '\0';
    printf("data: %s \n", dat);
    emscripten_fetch_close(fetch);
}

void requestOnError(emscripten_fetch_t *fetch)
{
    printf("HTTP failure status code: %d.\n", fetch->status);
    emscripten_fetch_close(fetch);
}

emscripten_fetch_attr_t attr;
emscripten_fetch_attr_init(&attr);
strcpy(attr.requestMethod, "GET");
attr.attributes = EMSCRIPTEN_FETCH_LOAD_TO_MEMORY;
attr.onsuccess = requestOnSuccess;
attr.onerror = requestOnError;
emscripten_fetch(&attr, "https://httpbin.org/anything");

Info