Json nodejs回调不工作

Json nodejs回调不工作,json,node.js,Json,Node.js,这是密码 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,

这是密码

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) {

将getData函数的第二个参数的名称更改为不同的callback->res。您在请求调用callback is a function中遇到名称冲突,您希望访问res变量

顺便说一句,如果请求是异步的,它将不起作用,因为在调用res.write之前调用res.end

编辑:


没有成功怎么办?你有什么错误吗?没有错误但没有写入结果不起作用,我想访问resthanks的写入方法,它起作用了!但是如果我必须改变if-ifres.writebody;这真的没有道理。res变量始终是可访问的。真正的问题在于回调。调用它不是为了删除if语句。但如果调用它,则必须保留语句:ifcallback&&typeofcallback===函数callbackbody;但是您确实知道res变量的值。但是如果我使用if callback&&typeof callback===函数不打印结果:/。那是错误的。如果您需要对回调执行某些操作,请将条件放在那里,然后调用回调。如果没有,只需调用res.write,无需任何条件。
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');