H
Hono2mo ago
Wazowski

relative pathname in Request not working on POST request

Using the pathname in a GET request everything works fine. Code:
test("GET: all car brands", async () => {
const res = await app.request("/api/brand");
const body = await res.json();
// [{ id: 0, name: "BMW" }, { id: 1, name: "Audi" }]
});
test("GET: all car brands", async () => {
const res = await app.request("/api/brand");
const body = await res.json();
// [{ id: 0, name: "BMW" }, { id: 1, name: "Audi" }]
});
But using a POST request I get the error: TypeError: Failed to construct 'Request': Invalid URL "/api/brand".
test("POST: create new car brand", async () => {
...
...
const req = new Request("/api/brand", {
method: "POST",
body: formData,
});

await app.request(req);
...
...

/*
41 | const req = new Request("/api/brand", {
^
TypeError: Failed to construct 'Request': Invalid URL "/api/brand"
code: "ERR_INVALID_URL"
*/
});
test("POST: create new car brand", async () => {
...
...
const req = new Request("/api/brand", {
method: "POST",
body: formData,
});

await app.request(req);
...
...

/*
41 | const req = new Request("/api/brand", {
^
TypeError: Failed to construct 'Request': Invalid URL "/api/brand"
code: "ERR_INVALID_URL"
*/
});
If I use the absolute server url (like http://localhost:3000/api/brand) it just works fine.
2 Replies
ambergristle
ambergristle2mo ago
using the test client might be easier than constructing the reqs yourself: https://hono.dev/docs/helpers/testing but my best guess would be that app.request is doing some relative path resolution under the hood that Request doesn't https://developer.mozilla.org/en-US/docs/Web/API/URL
Arjix
Arjix2w ago
you can make a POST request the same way you made the GET request the issue lies with constructing the Request instance, which you can avoid
test("create brand", async () => {
const res = await app.request("/api/brand", {
method: "POST",
body: formData
});
});
test("create brand", async () => {
const res = await app.request("/api/brand", {
method: "POST",
body: formData
});
});
think of app.request the same as window.fetch same API structure --- oops, necro bombing

Did you find this page helpful?