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

如何在Dart Shelf服务器的不同路由上提供不同静态文件?

在Shelf中为不同路由提供不同静态文件的解决方案

你的代码无法正常运行的核心问题是错误使用了get方法绑定静态处理器——get('/one', ...)只能匹配/one这个精确路径,无法处理该路由下的静态文件子路径(比如/one/js/app.js),同时静态处理器的文件路径解析会因为路由前缀的存在出现偏差。

下面是修正后的代码,同时优化了路径处理避免相对路径问题:

import 'dart:io';

import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart';
import 'package:shelf_router/shelf_router.dart';
import 'package:shelf_static/shelf_static.dart';

void main(List<String> args) async {
  final ip = InternetAddress.anyIPv4;

  // 使用绝对路径构建静态文件目录,避免相对路径的不确定性
  final oneStaticDir = Directory.current.parent.path + '/one/web';
  final twoStaticDir = Directory.current.parent.path + '/two/web';

  // 直接创建静态处理器,无需额外Pipeline包裹
  final staticHandler1 = createStaticHandler(oneStaticDir, defaultDocument: 'index.html');
  final staticHandler2 = createStaticHandler(twoStaticDir, defaultDocument: 'index.html');

  final router = Router()
    // 使用mount方法将静态处理器绑定到路由前缀,接管该前缀下的所有请求
    ..mount('/one/', staticHandler1)
    ..mount('/two/', staticHandler2);

  final port = int.parse(Platform.environment['PORT'] ?? '8080');
  final server = await serve(router, ip, port);
  print('Server listening on port ${server.port}');
}

关键修改说明:

  • 用mount替代get:mount('/one/', ...)会将所有以/one/开头的请求转发给静态处理器,确保子路径的静态文件能被正确匹配(比如访问/one/style.css时,处理器会去one/web/style.css查找文件)
  • 使用绝对路径:通过Directory.current构建绝对路径,避免因运行目录不同导致的文件找不到问题
  • 移除冗余Pipeline:createStaticHandler本身返回的就是符合Shelf标准的Handler,不需要额外用Pipeline包裹

现在你可以通过http://localhost:8080/one/访问one/web下的静态文件,通过http://localhost:8080/two/访问two/web下的静态文件,子资源也能正常加载。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 22:12:13