C++ 请求看起来像这样
emscripten_fetch_attr_t attr;
emscripten_fetch_attr_init(&attr);
strcpy(attr.requestMethod, "GET");
// case 1
// static std::vector<const char*> custom_headers = {"Token", "00000000", nullptr};
// attr.requestHeaders = custom_headers.data();
// case 2
static const char* custom_headers[3] = {"Token", "00000000-0000-0000-0000-000000000000", nullptr};
attr.requestHeaders = custom_headers;
attr.attributes = EMSCRIPTEN_FETCH_LOAD_TO_MEMORY;
attr.onsuccess = onDownload;
attr.onerror = onError;
emscripten_fetch(&attr, "http://localhost:9080/api/session");
XHR 工作正常,除了 header 字段 - 它们在两种情况下都没有设置。
来自 emscripten_fetch_attr_t
结构的文档评论说:
// Points to an array of strings to pass custom headers to the request. This array takes the form
// {"key1", "value1", "key2", "value2", "key3", "value3", ..., 0 }; Note especially that the array
// needs to be terminated with a null pointer.
const char * const *requestHeaders;
Emscripten FetchAPI reference和 code tests没有 requestHeaders
用法的示例。
我该如何设置自己的请求 header 字段?
最佳答案
它没有分配任何自定义 header 的原因真的很愚蠢——它在当前版本中还没有有效和经过测试的实现:
emscripten/1.37.13/system/lib/fetch/emscripten_fetch.cpp:第 78 行
fetch->__attributes.requestHeaders = 0;// TODO:strdup(fetch->__attributes.requestHeaders);
作为临时解决方案,只需将其分配给自己就足够了
fetch->__attributes.requestHeaders = fetch->__attributes.requestHeaders
然后您就可以使用我的问题中的第二种情况:
static const char* custom_headers[3] = {"Token", "00000000-0000-0000-0000-000000000000", nullptr};
attr.requestHeaders = custom_headers;
关于c++ - 如何从 C++ 为 emscripten Fetch API 设置自定义 header 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44671703/