fix bug with headers object and request objects passed into fetch

This commit is contained in:
ading2210 2024-09-11 13:31:57 -04:00
parent 754b211c59
commit 3c1a942501
2 changed files with 17 additions and 6 deletions

View file

@ -96,13 +96,18 @@ class HTTPSession extends CurlSession {
});
}
async fetch(resource, params={}) {
async fetch(resource, params_old={}) {
let url = resource;
//shallow copy the original params object
let params = Object.fromEntries(Object.entries(params_old));
if (resource instanceof Request) {
url = resource.url;
params.body = params.body || await resource.blob();
params.headers = params.headers || Object.fromEntries(resource.headers);
params.method = params.method || resource.method;
let resource_body = await resource.arrayBuffer();
if (resource_body.byteLength !== 0)
params.body = resource_body;
}
else if (typeof url === "string" || url instanceof String) {
url = (new URL(url, this.base_url)).href;
@ -169,10 +174,8 @@ class HTTPSession extends CurlSession {
}
let headers = params.headers || {};
if (params.headers instanceof Headers) {
for(let [key, value] of headers) {
headers[key] = value;
}
if (headers instanceof Headers) {
headers = Object.fromEntries(headers);
}
params.headers = new HeadersDict(headers);

View file

@ -1,5 +1,13 @@
async function test() {
//regular fetch
let r = await libcurl.fetch("https://example.com/");
assert(r.status === 200, "wrong status");
await r.text();
//fetch with request object
let options = {headers: new Headers({"x-test-header": "1"})};
let r2 = await libcurl.fetch(new Request("https://httpbin.org/get", options));
assert(r2.status === 200, "wrong status");
let r2_json = await r2.json();
assert(r2_json.headers["X-Test-Header"] === "1");
}