是代码
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');
我需要打印我得到的内容,我尝试使用回调但没有成功。我不明白出了什么问题。我认为错误在这一行或功能错误
request(urlData, function(error, response, body, callback) {
答案 0 :(得分:0)
将getData函数的第二个参数的名称更改为不同的名称(callback - > res)。在请求调用中有一个名称冲突(回调是一个函数,你想访问res变量)。
顺便说一句,如果请求是异步的,那么它就无法工作,因为你在调用res.write()之前调用res.end()。
编辑:
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');