mirror of
https://github.com/ading2210/libcurl.js.git
synced 2025-05-13 14:30:02 -04:00
fix bug with headers object and request objects passed into fetch
This commit is contained in:
parent
754b211c59
commit
3c1a942501
2 changed files with 17 additions and 6 deletions
|
@ -96,13 +96,18 @@ class HTTPSession extends CurlSession {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async fetch(resource, params={}) {
|
async fetch(resource, params_old={}) {
|
||||||
let url = resource;
|
let url = resource;
|
||||||
|
//shallow copy the original params object
|
||||||
|
let params = Object.fromEntries(Object.entries(params_old));
|
||||||
|
|
||||||
if (resource instanceof Request) {
|
if (resource instanceof Request) {
|
||||||
url = resource.url;
|
url = resource.url;
|
||||||
params.body = params.body || await resource.blob();
|
|
||||||
params.headers = params.headers || Object.fromEntries(resource.headers);
|
params.headers = params.headers || Object.fromEntries(resource.headers);
|
||||||
params.method = params.method || resource.method;
|
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) {
|
else if (typeof url === "string" || url instanceof String) {
|
||||||
url = (new URL(url, this.base_url)).href;
|
url = (new URL(url, this.base_url)).href;
|
||||||
|
@ -169,10 +174,8 @@ class HTTPSession extends CurlSession {
|
||||||
}
|
}
|
||||||
|
|
||||||
let headers = params.headers || {};
|
let headers = params.headers || {};
|
||||||
if (params.headers instanceof Headers) {
|
if (headers instanceof Headers) {
|
||||||
for(let [key, value] of headers) {
|
headers = Object.fromEntries(headers);
|
||||||
headers[key] = value;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
params.headers = new HeadersDict(headers);
|
params.headers = new HeadersDict(headers);
|
||||||
|
|
||||||
|
|
|
@ -1,5 +1,13 @@
|
||||||
async function test() {
|
async function test() {
|
||||||
|
//regular fetch
|
||||||
let r = await libcurl.fetch("https://example.com/");
|
let r = await libcurl.fetch("https://example.com/");
|
||||||
assert(r.status === 200, "wrong status");
|
assert(r.status === 200, "wrong status");
|
||||||
await r.text();
|
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");
|
||||||
}
|
}
|
Loading…
Add table
Add a link
Reference in a new issue