Can't get serveStatic to work with `root`
I'm a bit confused here:
app.use("/static/*", serverStatic({ root: "./static"}))
can't resolve /static/myscript.js
But app.use("/myscript", serveStatic({ path: "./static/assets/myscript.js"})
does work when accessing /myscript
Folder structure is:
- src
- static
- assets
- myscript.js17 Replies
I'm using bun
can you share a bit more about what's going on?
if root is
./static
, then ./static/assets/myscript.js
duplicates the first segment, no?Hmm, could that mean that root is not being set?
Btw I also tried accessing it via
/static/assets/myscript.js
when only setting root, didn't work either
There's nothing else going on. I only created a fresh project so it's all very isolatedsorry for the confusion. i was asking for additional detail on what you're trying to accomplish and what's going wrong
Just trying to serve a js file statically. (also tried serving an html file for testing)
that's not really enough for me to understand or reproduce your issue
What else do you need?
the request paths you're using and the response error would be helpful
Getting 404s
app.use("/static/*", serveStatic({ root: "./static"}))
is what I use to set the root
Then I want to access the file via this URL: /static/myscript.js
also tried /static/assets/myscript.js
If I do this: app.use("/static/*", serveStatic({ root: "./"}))
I can access the file via this URL /static/assets/myscript.js
yeah. the
/static/*
is confusing the middleware, though i'm not sure why yet
ah, it's this: https://github.com/honojs/hono/blob/be0dbd6f862efcdbdb4d9f6f2013989162c3e088/src/middleware/serve-static/index.ts#L61Probably I'm just misunderstanding how it's supposed to work
i wouldn't expect
/static/*
to be included in the file path used either
definitely not clear from the docsHow I understand it is:
app.use("static/*"
should resolve all files for URLs starting with /static
and serveStatic({root: "./static"})
means it should start looking for the files in the /static
directory
So if my URL is /static/someFile.txt
it should be available at URL /someFile.txt
?it gets doubled up
the middleware uses the full request path, including the
/static/*
so either of these will work:
Damns son, paths are complicated
Why does this not work?
app.use("/static/*", serverStatic({ root: "./static"}))
If my file is in /static/assets/myfile.txt
Then my expectation was that I can cut the /static
from he URL and access it like /assets/myfile.txt
Guess it's the exact opposite of what I was thinking hahabecause you're specifying
/static
twice, so the resolved file path becomes /static/static/assets/myfile.txt
check out the link i shared
the middleware doesn't know what part of the path (i.e., /static/*
) is for app routing, and what part is the file path
so when you double up:
it looks for a /static
directory in the /static
directoryAight, thanks. Need to come back later to revisit it. Brain capacity doesn't allow it at the moment