dart - 在 Dart 服务器上正确使用 'route' 和 'path' 库

标签 dart server

我正在寻找有关如何改进此文件服务器的指导。

目前它无法处理 POST,因为每个请求都会传递给 http_server 库。它还会简单地路由 URL;可以使用路由器来改进吗?也许 path lib 也能提供帮助?

import 'dart:io';
import 'package:http_server/http_server.dart';

// TODO: use these imports :)
import 'package:path/path.dart' as path;
import 'package:route/url_pattern.dart';

final address = InternetAddress.LOOPBACK_IP_V4;
const port = 4040;

final buildPath = Platform.script.resolve('web');
final publicDir = new VirtualDirectory(buildPath.toFilePath());

main() async {
  // Override directory listing
  publicDir
    ..allowDirectoryListing = true
    ..directoryHandler = handleDir
    ..errorPageHandler = handleError;

  // Start the server
  final server = await HttpServer.bind(address, port);
  print('Listening on port $port...');
  await server.forEach(publicDir.serveRequest);
}

// Handle directory requests
handleDir(dir, req) async {
  var indexUri = new Uri.file(dir.path).resolve('index.html');
  var index = new File.fromUri(indexUri);
  if (!await index.exists()) {
    handleError(req);
    return;
  }
  publicDir.serveFile(index, req);
}

// Handle error responses
handleError(req) {
  req.response.statusCode = HttpStatus.NOT_FOUND;
  var errorUri = new Uri.directory(publicDir.root).resolve('error.html');
  var errorPage = new File.fromUri(errorUri);
  publicDir.serveFile(errorPage, req);
}

最佳答案

我没有找到解决这个问题的方法

await for (var req in server) {
  // distribute requests to different handlers
  if(req.method == 'POST') {

  } else {
    publicDir.serveRequest(req);
  }
}

或者,您可以使用带有 shelf_routeshelf_staticshelf 包,它允许您以更具声明性的风格分配请求和处理程序,但在引擎盖下做同样的事情

https://pub.dartlang.org/search?q=shelf_static

关于dart - 在 Dart 服务器上正确使用 'route' 和 'path' 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33597740/

相关文章:

dart - PlatformException (PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException : 12500: , null))

dart - Flutter:在多个列表或列之间排序、拖放

server - 如何通过FileZilla访问Google Kubernetes引擎FTP服务器

javascript - Node.JS 错误 - process.env.NODE_TLS_REJECT_UNAUTHORIZED。这是什么意思?

listview - Flutter:Listview渲染库问题:垂直视口(viewport)被赋予无限宽度

android - VScode : avdmanager is missing from the Android SDK

dart - 将 onGenerateRoute 与 Flutter 后退按钮一起使用时断言失败

amazon-ec2 - 将 Amazon EC2 实例从上一代更新到最新版本

java - 将客户端/游戏 session 验证从一台服务器传递到另一台服务器? ( java )

ubuntu - Virtualbox - 找不到适合运行内核的模块