Tuesday, May 28, 2024
 Popular · Latest · Hot · Upcoming
37
rated 0 times [  44] [ 7]  / answers: 1 / hits: 16501  / 8 Years ago, sat, april 16, 2016, 12:00:00

I am having trouble with a Node.js http request. (A bigger question I will ask about later if I can't figure it out).



I have code that I modified from and an example and I don't understand what the response.on means. As read more about http in Node.js (Anatomy of an HTTP Transaction) I don't see people using examples with 'response.on'. I think I know but I want to clarify. Oh I am using Express.js too.



Thanks



Below is the code I am using to try and call the BART api I need a response from.



...
// Real Time Departure from a given station
router.route('/departTimeStation')
.get(function(req, res) {
vCmd = 'etd';
vOrig = req.query.vOriginStation;
vDir = 'n'; // [NOTE] - 'n' or 's', north or south, OPTIONAL
vPlat = 1; // [NOTE] - 1 to 4, number of platform, OPTIONAL

var xoptions = {
host: 'api.bart.gov',
path: '/api/etd.aspx?cmd=' + vCmd + '&orig=' + vOrig + '&key=' + config.bart.client
};

var xcallback = function(response) {

response.on('data', function(chunk) {
vParsed += chunk;
});

response.on('end', function() {
parseString(vParsed, function(err, result) {
vShow = JSON.stringify(result);
vTemp = result;
});
});
};
http.request(xoptions, xcallback).end();
return res.send (vTemp)
});
...

More From » node.js

 Answers
14

response.on can take a few 'events' that happen during the response life cycle,



The two you have above are response.on('data'...) which is when you get the data
and response.on('end'...) is at the end of the response, simple as that!



Node Docs on response: https://nodejs.org/api/http.html#http_class_http_incomingmessage


[#62533] Thursday, April 14, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
eanskylerg

Total Points: 524
Total Questions: 107
Total Answers: 100

Location: Colombia
Member since Mon, May 2, 2022
2 Years ago
;