0

我正在尝试将以下 Node.js 片段转换为 Dart。在我的转换中,只要有响应就会打印“返回的数据...”消息,这与 Node.js 版本不同,该版本会等到页面完成请求的 2 秒延迟。

节点.js

var http = require('http')    
function fetchPage() {
  console.log('fetching page');
  http.get({ host: 'trafficjamapp.herokuapp.com', path: '/?delay=2000' }, function(res) {
    console.log('data returned from requesting page');
  }).on('error', function(e) {
    console.log("There was an error" + e);
  });
}

import 'dart:io';
import 'dart:uri';

fetchPage() {
  print('fetching page');
  var client = new HttpClient();
  var uri = new Uri.fromComponents(scheme:'http', domain: 'trafficjamapp.herokuapp.com', path: '?delay=2000');
  var connection = client.getUrl(uri);

  connection.onRequest = (HttpClientRequest req) {
    req.outputStream.close();
  };

  connection.onResponse = (HttpClientResponse res){
    print('data returned from requesting page');
  };

  connection.onError = (e) => print('There was an error' ' $e');
}

如何在 Dart 中实现与在 Node 中相同的延迟打印?提前致谢。

4

2 回答 2

1

您可以在onResponse回调的文档中找到它:

当收到响应的所有标头并准备好接收数据时,将调用回调。

所以它是这样工作的:

connection.onResponse = (res) {
  print('Headers received, can read the body now');
  var in = res.inputStream;

  in.onData = () {
    // this can be called multiple times
    print('Received data');
    var data = in.read();
    // do something with data, probably?
  };
  in.onClosed = () {
    // this is probably the event you are interested in
    print('No more data available');
  };
  in.onError = (e) {
    print('Error reading data: $e');
  };
};
于 2012-11-14T07:11:18.680 回答
1

你的 Dart 代码几乎是正确的,但是有一个错误。您应该使用query命名参数而不是path. 我真的不知道您的代码调用了哪个 Url,但响应有一个400状态代码。为了提高可读性,您还可以使用Uri.fromString构造函数。

此外,您可以省略您的onRequest设置,因为在onRequest未定义时执行相同的代码。

这是代码:

import 'dart:io';
import 'dart:uri';

main() {
  print('fetching page');
  //var uri = new Uri.fromString('http://trafficjamapp.herokuapp.com/?delay=2000');
  var uri = new Uri.fromComponents(scheme:'http',
      domain: 'trafficjamapp.herokuapp.com', query: 'delay=2000');
  var client = new HttpClient();
  var connection = client.getUrl(uri);
  connection.onResponse = (HttpClientResponse res){
    print('data returned from requesting page with status ${res.statusCode}');
  };
  connection.onError = (e) => print('There was an error' ' $e');
}
于 2012-11-14T08:51:27.313 回答