在Hono中搭配serveStatic使用basicAuth触发SIGSEGV错误,求解决方案
Hono中serveStatic搭配basicAuth触发SIGSEGV错误的解决方案
问题现象
在Hono框架中,尝试给serveStatic中间件搭配basicAuth使用时触发SIGSEGV错误,但在app.get等HTTP方法路由中使用basicAuth却能正常工作。
错误信息
error: script "dev" was terminated by signal SIGSEGV (Address boundary error)
原示例代码
import { Hono } from "hono"; import { basicAuth } from "hono/basic-auth"; import { serveStatic } from "hono/bun"; const app = new Hono(); const auth = basicAuth({ username: "password", password: "password", }); app.use("/*", auth); app.use("/static/*", auth, serveStatic({ root: "./" })); Bun.serve({ port: 8000, fetch: app.fetch });
解决方案
问题出在重复添加了basicAuth中间件:全局通过app.use("/*", auth)已经为所有路由(包括/static/*)启用了身份验证,随后又在/static/*的路由规则里再次添加了auth中间件,这种重复执行可能导致内存访问异常,触发SIGSEGV错误。
调整代码的两种方式:
- 保留全局身份验证,移除
/static/*中的重复auth:
import { Hono } from "hono"; import { basicAuth } from "hono/basic-auth"; import { serveStatic } from "hono/bun"; const app = new Hono(); const auth = basicAuth({ username: "password", password: "password", }); // 全局启用身份验证,所有路由都生效 app.use("/*", auth); // 静态文件路由不再重复添加auth app.use("/static/*", serveStatic({ root: "./" })); Bun.serve({ port: 8000, fetch: app.fetch });
- 仅给静态文件路由添加身份验证,移除全局auth(如果其他路由不需要验证):
import { Hono } from "hono"; import { basicAuth } from "hono/basic-auth"; import { serveStatic } from "hono/bun"; const app = new Hono(); const auth = basicAuth({ username: "password", password: "password", }); // 仅静态文件路由启用身份验证 app.use("/static/*", auth, serveStatic({ root: "./" })); // 其他路由正常定义 app.get("/", (c) => c.text("Public page")); Bun.serve({ port: 8000, fetch: app.fetch });
另外注意:serveStatic的root配置指向当前目录./,确保/static/*对应的文件路径正确,避免因文件不存在或权限问题引发额外异常。
内容的提问来源于stack exchange,提问作者Ali Khosro
相关产品推荐
相关产品推荐

