I’m trying to convert the following Node.js snippet to Dart. In my conversion the ‘data returned…’ message is printed as soon as there is a response unlike in the Node.js version which waits until the page completes the requested 2 second delay.
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);
});
}
Dart
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');
}
How do I achieve the same delayed print in Dart as in Node? Thanks in advance.
Your Dart code was almost right, but there was a bug. You should have used
querynamed parameter instead ofpath. I don’t really know which Url is call with your code but the response has a400status code. For more readability, you can also use theUri.fromStringconstructor.Moreover you can omit your
onRequestsetting because the same code is done whenonRequestis not defined.Here’s the code :