是否可以使用WebAssembly提交HTTP请求?

DP_*_*DP_ 11 c http xmlhttprequest emscripten webassembly

我正在尝试在WebAssembly中提交一个简单的HTTP GET请求.为此,我编写了这个程序(从Emscripten网站复制,稍作修改):

#include <stdio.h>
#include <string.h>
#ifdef __EMSCRIPTEN__
#include <emscripten/fetch.h>
#include <emscripten.h>
#endif


void downloadSucceeded(emscripten_fetch_t *fetch) {
  printf("Finished downloading %llu bytes from URL %s.\n", fetch->numBytes, fetch->url);
  // The data is now available at fetch->data[0] through fetch->data[fetch->numBytes-1];
  emscripten_fetch_close(fetch); // Free data associated with the fetch.
}

void downloadFailed(emscripten_fetch_t *fetch) {
  printf("Downloading %s failed, HTTP failure status code: %d.\n", fetch->url, fetch->status);
  emscripten_fetch_close(fetch); // Also free data on failure.
}

unsigned int EMSCRIPTEN_KEEPALIVE GetRequest() {
  emscripten_fetch_attr_t attr;
  emscripten_fetch_attr_init(&attr);
  strcpy(attr.requestMethod, "GET");
  attr.attributes = EMSCRIPTEN_FETCH_LOAD_TO_MEMORY;
  attr.onsuccess = downloadSucceeded;
  attr.onerror = downloadFailed;
  emscripten_fetch(&attr, "http://google.com");
  return 1;
}
Run Code Online (Sandbox Code Playgroud)

当我使用我编译它时,$EMSCRIPTEN/emcc main.c -O1 -s MODULARIZE=1 -s WASM=1 -o main.js --emrun -s FETCH=1我得到了错误

ERROR:root:FETCH not yet compatible with wasm (shared.make_fetch_worker is asm.js-specific)
Run Code Online (Sandbox Code Playgroud)

有没有办法从WebAssembly运行HTTP请求?如果是,我该怎么办?

更新1:以下代码尝试发送GET请求,但由于CORS问题而失败.

#include <stdio.h>
#include <string.h>
#ifdef __EMSCRIPTEN__
#include <emscripten/fetch.h>
#include <emscripten.h>
#endif

unsigned int EMSCRIPTEN_KEEPALIVE GetRequest() {
  EM_ASM({
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "http://google.com");
    xhr.send();
  });
  return 1;
}
Run Code Online (Sandbox Code Playgroud)

Col*_*inE 7

不,您不能从 WebAssembly 执行 HTTP 请求(或访问 DOM 或任何其他浏览器 API)。WebAssembly 本身无法访问其主机环境,因此它没有任何内置的 IO 功能。

但是,您可以从 WebAssembly 导出函数,并从宿主环境导入函数。这将允许您通过主机间接发出 HTTP 请求。


sbc*_*100 6

我最近遇到了这个问题,esmcripten修复了它:https://github.com/kripken/emscripten/pull/7010

您现在应该能够一起使用FETCH = 1和WASM = 1.