我正在尝试将以下Node.js代码段转换为Dart。在我的转换中,一旦有响应就打印出'data returned ...'消息,这与Node.js版本不同,后者等待页面完成请求的2秒延迟。
Node.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中实现与节点相同的延迟打印?提前谢谢。
答案 0 :(得分: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');
};
};
答案 1 :(得分: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');
}