You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mac下Deno静态服务器无法加载index.html的404问题求助

解决Deno Oak静态服务器无法识别index.html的404问题

核心排查方向:自定义静态中间件配置问题

你导入的staticServer来自../shared/server.ts,大概率是这个模块里的静态服务配置没有正确指定默认索引文件或根目录路径,导致访问根路径时找不到index.html。

1. 修正shared/server.ts的静态服务配置

打开../shared/server.ts,确保serveStatic的配置包含root和index参数:

import { serveStatic } from "https://deno.land/x/oak@v12.6.1/mod.ts";

// 配置静态服务:指定根目录为public,默认索引文件为index.html
export const staticServer = serveStatic({
  root: `${Deno.cwd()}/public`, // 确保路径指向hello_web.js同级的public文件夹
  index: "index.html", // 关键:设置访问根路径时默认加载的文件
});

export function createExitSignal() {
  const controller = new AbortController();
  Deno.addSignalListener("SIGINT", () => controller.abort());
  Deno.addSignalListener("SIGTERM", () => controller.abort());
  return controller.signal;
}

2. 验证文件路径与权限

  • 确认public/index.html确实在hello_web.js的同级目录下,路径没有层级错误
  • 运行以下命令检查文件是否可访问:
    deno run --allow-read --eval "console.log(await Deno.stat('./public/index.html'))"
    
  • 启动服务器时必须添加--allow-net和--allow-read权限:
    deno run --allow-net --allow-read hello_web.js
    

3. 绕过自定义模块,直接在主文件配置静态服务

如果不确定shared/server.ts的问题,可以直接在hello_web.js中配置静态服务,排除模块引入的干扰:

import { Application, serveStatic } from "https://deno.land/x/oak@v12.6.1/mod.ts";
import { createExitSignal } from "../shared/server.ts";

const app = new Application();
// 直接配置静态服务,避免依赖自定义模块的潜在问题
app.use(serveStatic({
  root: `${Deno.cwd()}/public`,
  index: "index.html",
}));

console.log("\nListening on http://localhost:8000");
await app.listen({ port: 8000, signal: createExitSignal() });

测试这个版本,如果能正常访问localhost:8000,则问题确实出在shared/server.ts的配置上。

4. 确认版本兼容性

你使用的Deno 1.42.1与Oak v12.6.1版本兼容,但如果以上步骤都无效,可以尝试重新安装依赖:

deno cache --reload https://deno.land/x/oak@v12.6.1/mod.ts

内容的提问来源于stack exchange,提问作者Mai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 03:33:20