Dart HttpRequest POST 进程无法在函数调用中存活

Dart HttpRequest POST process doesn't survive function calls

我有一个接收 POST 请求的 Dart 服务器,如果我立即用 await utf8.decoder.bind(request).join() 读取 POST 正文,我可以毫无问题地获取内容。如果我将 HttpRequest 传递给一个函数以使用相同的代码处理正文,我会得到一个 HttpException:HttpException: Connection closed while receiving data, uri = /v1/auth/apple。我无法控制 POST,因为它是作为 redirectURI 从 Apple 身份验证服务器发送到我的服务器的。为什么将 HttpRequest 传递给函数会导致失败?

POST 正文是 URL 编码字符串。

Dart SDK 版本:2.12.0-141.0.dev (dev)

这是基本路由器:

void route(HttpServer httpsServer) async {
    await for (HttpRequest request in httpsServer) {
      switch (request.method) {
        case 'GET':
          _getRouter.route(request);
          break;
        case 'POST':
          if (request.uri.path == '/v1/auth/apple') {
            // If I execute this function, the POST processing fails
            // with the HttpException
            postTest(request);
            // If I execute the identical code from the function inline here
            // then it reads the body of the POST without issue
            var requestBody = await utf8.decoder.bind(request).join();
            var requestUri = Uri(query: requestBody);
            _getRouter.v1Auth(request, uri: requestUri);
          } else {
            _postRouter.route(request);
          }
          break;
        default:
          request.response.statusCode = HttpStatus.methodNotAllowed;
      }
      await request.response.flush();
      await request.response.close();
    }

// Attempting to process the POST body in this function causes
// an HttpExeception: Connection closed while receiving data
void postTest(HttpRequest request) async {
    var requestBody = await utf8.decoder.bind(request).join();
    var requestUri = Uri(query: requestBody);
    _getRouter.v1Auth(request, uri: requestUri);
  }

您没有await使用您的异步函数postTestpostTest 应该 returning Future<void> 而不是 void。

那你就可以await postTest(request);正常了。

应该有一些 linter 规则,您可以启用这些规则以在您不等待异步函数中的未来时警告您,并且可以将所有异步函数强制执行到 return 未来。

您可以阅读有关自定义静态分析的更多信息 here. I think the specific rules 您正在寻找的是 avoid_void_asyncunawaited_futures