How to serve static files in Node.js using Hono.js?

979 views Asked by At

I am using Hono.js for Node.js to build an API. And for serving static file I am using serveStatic middleware.

user.use("/static/*", serveStatic({ root: "./" }));
user.get("/signin", serveStatic({ path: '../public/signin.html'}));

I also tried this -

user.get("/signin", serveStatic({ root: "./", rewriteRequestPath: (path) => path.replace(/^\/signin/, '/public')}));

The signin.html file in under public directory in the root dir. When I am sending a text or json using c.text or c.json, the expected output is shown. Which implies that routing is correct.

But using this code, the output is

<-- GET /user/signin
--> GET /user/signin 404 9ms

Any idea how to solve this ? How to serve files or send files as a response to any request ?

1

There are 1 answers

2
Adophilus On

It would seem that by default the serveStatic middleware would match the pat h starting from the current directory (where the hono app was started).

I have my hono app setup like so: enter image description here

And I have the following directory structure: enter image description here

Notice the static folder at the project root.

So that when a request hits up /static/file.json it'll return the file located at the same path.

Here's the end result (if you've got everything setup correctly): enter image description here