I am using node.js with express. There is a button that the user can click, and doing so calls this method on the server:
app.get('/getTime', function(req, res) {
var url = 'http://www.ctabustracker.com/bustime/api/v1/gettime';
http.get(url + '?key=' + apikey, function(resp) {
var xml = '';
resp.on('data', function(chunk) {
xml += chunk;
});
resp.on('end', function() {
console.log(xml);
res.send(xml);
});
});
});
This works, strictly speaking, in that the client side does receive the XML data. What bothers me is that there are two response objects that I have only dealt with by calling one "res" and the other "resp". I have a feeling I am handling the callbacks the wrong way, or that the entire structure of this task is done incorrectly.
I would appreciate some guidance about the "right way" to do this, as I am sure this is not it.
2 Answers 2
Since the HTTP response implements Writable Stream
and Express wraps around HTTP, you can pipe the output to the response, like so:
app.get('/getTime', function(req, res) {
var url = 'http://www.ctabustracker.com/bustime/api/v1/gettime';
http.get(url + '?key=' + apikey, function(incoming) {
incoming.pipe(res);
}
});
It will not only cut down on latency times but also cut down on lines of code.
-
\$\begingroup\$ That's excellent, thanks very much. I knew there was something I wasn't quite seeing and this is it. \$\endgroup\$Will– Will2014年09月20日 13:40:02 +00:00Commented Sep 20, 2014 at 13:40
From a once over:
- Your indenting is off, try something like jsbeautifier.org
- Dont do
console.log
in production code, it is synchronous and slow - Other than that your code is very typical, there is nothing obviously wrong
Furthermore, would this work for you ?
app.get('/getTime', function(req, res) {
var url = 'http://www.ctabustracker.com/bustime/api/v1/gettime';
http.get(url + '?key=' + apikey, res);
});
Since you are anyway sending the data thru, I wonder if this would work.