【发布时间】:2019-02-05 17:28:49
【问题描述】:
我正在尝试在 WebAssembly 中提交一个简单的 HTTP GET 请求。为此,我编写了这个程序(复制自Emscripten site,稍作修改):
#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;
}
当我使用 $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)
有没有办法从 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;
}
【问题讨论】:
-
答案和stackoverflow.com/questions/52078564/…差不多。您可以从 Webassembly 导入一个知道如何发出请求的 JS 函数和
call它
标签: c http xmlhttprequest emscripten webassembly