0

我有一个在服务器端运行的 Dart 应用程序。它正在侦听特定端口并且工作正常。问题是:我的听众正在响应最喜欢的图标(favicon)的 GET。

我怎样才能避免这种情况?

编辑:给出一些代码示例。

import 'dart:io';

void main() {
    print("Starting server.");
    HttpServer.bind(InternetAddress.LOOPBACK_IP_V4, 4041)
        .then(listenForRequests)
        .catchError((e) => print (e.toString()));
}

listenForRequests(HttpServer _server) {
    _server.listen((HttpRequest request) {
        if (request.method == 'GET') {
            handleGet(request);
        } else {
            request.response.statusCode = HttpStatus.METHOD_NOT_ALLOWED;
            request.response.write("Unsupported request: ${request.method}.");
            request.response.close();
        }
    },
    onDone: () => print('No more requests.'),
    onError: (e) => print(e.toString()) );
}

void handleGet(HttpRequest request) {
    int requestNumber = 1;
    print(requestNumber); // This shows me the request number. Just for information.
    print(request.uri); // This shows me the request from the client browser.
    request.response.statusCode = HttpStatus.OK;
    request.response.close();
}

这是这段代码的输出:

1

/SOME_REQUEST_FROM_THE_BROWSER

2

/favicon.ico

4

1 回答 1

2

您可以检查请求的资源并为对“favicon.ico”的请求生成正确的响应,例如

void handleGet(HttpRequest request) {
    int requestNumber = 1;
    print(requestNumber++); // This shows me the request number.
    print(request.uri); // This shows me the request from the client browser.
    if(request.requestedUri.path != '/favicon.ico') {
      request.response.statusCode = HttpStatus.NOT_FOUND;
    } else {
      request.response.statusCode = HttpStatus.OK;
    }
    request.response.close();
}
于 2014-06-27T14:48:03.337 回答