it is the code
var http = require('http');
var request = require("request");
function getData(city, callback){
var urlData = 'http://api.openweathermap.org/data/2.5/weather?q='+city;
callback.write("urlRequest : "+urlData+"\n");
request(urlData, function(error, response, body, callback) {
if(callback && typeof(callback) === "function")
callback.write(body);
});
}
// create http server
http.createServer(function (req, res) {
var query = require('url').parse(req.url).query;
var app = require('querystring').parse(query).city;
// content header
res.writeHead(200, {'Content-Type': 'text/plain'});
if(app)
getData(app, res);
else
res.write("Use url:port?city=xxxx");
res.end();
}).listen(8124);
console.log('Server running at 8124');
I need to print what I get, I tried to use a callback but did not succeed. I do not understand what is wrong. I think the error is in this line or the function is wrong
request(urlData, function(error, response, body, callback) {
Change the name of the second parameter of the getData function to something different (callback -> res). You have a names collision inside of the request call (callback is a function and you want to access the res variable).
By the way, if the request is asynchronous, it's not going to work, because you call res.end() before the res.write() is called.
Edit:
var http = require('http');
var request = require("request");
function getData(city, res){ // Here
var urlData = 'http://api.openweathermap.org/data/2.5/weather?q='+city;
res.write("urlRequest : "+urlData+"\n"); // Here
request(urlData, function(error, response, body, callback) {
if(callback && typeof(callback) === "function")
res.write(body); // Here
res.end(); // Here
});
}
// create http server
http.createServer(function (req, res) {
var query = require('url').parse(req.url).query;
var app = require('querystring').parse(query).city;
// content header
res.writeHead(200, {'Content-Type': 'text/plain'});
if(app) {
getData(app, res);
}
else {
res.write("Use url:port?city=xxxx");
res.end(); // Here
}
}).listen(8124);
console.log('Server running at 8124');