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

Ts.ED开发SPA项目静态资源无法访问返回404错误求助

解决方案

  1. 检查是否安装@tsed/serve-static依赖
    静态资源服务是Ts.ED的可选扩展模块,开发过程中如果误删该依赖,statics配置会直接静默失效,不会抛出任何错误提示,完全符合你遇到的现象。执行对应包管理命令安装即可恢复功能:
npm install @tsed/serve-static
# 或使用yarn、pnpm对应的安装命令
  1. 验证静态资源路径正确性
    你代码中已经打印了clientDir路径,可直接进入该路径确认index.html文件是否存在,避免编译后目录结构和预期不符的问题。
  2. 手动挂载降级方案
    如果确认依赖安装正常仍无法生效,可以绕过Ts.ED的statics配置项,手动在生命周期钩子中挂载express原生静态中间件,修改后的代码参考:
import { join } from "path";
import { $log, Configuration, Inject, PlatformApplication, OnMount } from "@tsed/common";
import { PlatformExpress } from "@tsed/platform-express";
import express from "express";
import config from '@config';

const rootDir = __dirname;
const clientDir = join(rootDir, '../client');
console.log('clientDir: ' + clientDir);

@Configuration({
    rootDir,
    port: config.http.port
})
export class Server implements OnMount {
  @Inject()
  app: PlatformApplication;

  $onMount() {
    // 手动挂载静态资源,优先级高于后续接口路由
    this.app.use(express.static(clientDir));
    // 可选配置:SPA前端路由回退,解决路由刷新404问题
    this.app.get('*', (req, res) => {
      res.sendFile(join(clientDir, 'index.html'));
    })
  }
}

async function bootstrap() {
    try {
        $log.debug("Start server...");
        const platform = await PlatformExpress.bootstrap(Server, {});
        await platform.listen();
        $log.debug("Server initialized");
    } catch (er) {
        $log.error(er);
    }
}

bootstrap();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 12:36:04