Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/468.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Node.js TypeError:无法调用方法';写';未定义的_Javascript_Node.js - Fatal编程技术网

Javascript Node.js TypeError:无法调用方法';写';未定义的

Javascript Node.js TypeError:无法调用方法';写';未定义的,javascript,node.js,Javascript,Node.js,这是nodejs中用于调用openweather API并在127.0.0.7:8124上打印结果的代码,但不理解为什么它不起作用 var http = require('http'); function getData(city, res){ var urlData = 'http://api.openweathermap.org/data/2.5/weather?q='+city; http.get(urlData, function(resi) { va

这是nodejs中用于调用openweather API并在127.0.0.7:8124上打印结果的代码,但不理解为什么它不起作用

var http = require('http');

function getData(city, res){
    var urlData = 'http://api.openweathermap.org/data/2.5/weather?q='+city;

    http.get(urlData, function(resi) {
        var body = '';

        resi.on('data', function(chunk) {
            body += chunk;
        });

        resi.on('end', function() {
            var dataResponse = JSON.parse(body)
            res.write(dataResponse);
        });
    }).on('error', function(e) {
          res.write("Got error: " + e);
    });
}

// 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){
        console.log("ad: "+getData(app));
    } else res.write("Use url:port?city=xxxx");

    res.end();
}).listen(8124);
console.log('Server running at 8124');
这就是错误所在

overflow@overflow-1015cx:~/Scrivania/nodeweather$ node app.js 
Server running at 8124
ad: undefined

/home/overflow/Scrivania/nodeweather/app.js:15
        res.write(dataResponse);
            ^
TypeError: Cannot call method 'write' of undefined
    at IncomingMessage.<anonymous> (/home/overflow/Scrivania/nodeweather/app.js:15:13)
    at IncomingMessage.EventEmitter.emit (events.js:117:20)
    at _stream_readable.js:920:16
    at process._tickCallback (node.js:415:13)
overflow@overflow-1015cx:~/Scrivania/nodeweather$ 
overflow@overflow-1015cx:~/Scrivania/nodewather$node app.js
在8124运行的服务器
广告:未定义
/home/overflow/Scrivania/nodewather/app.js:15
res.write(数据响应);
^
TypeError:无法调用未定义的方法“write”
在收到消息时。(/home/overflow/Scrivania/nodewather/app.js:15:13)
在IncomingMessage.EventEmitter.emit(events.js:117:20)
at_stream_readable.js:920:16
在进程中调用(node.js:415:13)
overflow@overflow-1015cx:~/Scrivania/nodewather$

为什么我不能返回结果?

您没有将响应对象传递到getData中

我相信它应该是这样的,但我还没有测试过

 if(app){
        console.log("ad: "+getData(app,res));
    } else res.write("Use url:port?city=xxxx");\
如果你读到了这个错误,它并没有告诉你你不能写,而是说你试图在一个空对象上调用write。如果您跟踪有关
res
如何可以为null的线索,应该会变得清晰。

Nodejs是异步的,res.end()在http请求中res.write之前被调用。。因此,您需要使用一些“承诺”技术或至少回调。但是,这段代码无法工作,因为您正在尝试编写解析的json字符串,但是write方法只接受字符串或缓冲区…而且getData不会返回任何内容..因此console.log(“ad:+getData(app,res,res.end));打印未定义的变量

也许此代码更符合您的想法(使用“rome”进行测试和工作):


res
resi
?我不认为res有任何意义。“resi”是函数getdata中的变量“res”。我认为他把事情搞得一团糟!不工作,这是在8124 ad:undefined http.js:853 throw new TypeError(第一个参数必须是字符串或缓冲区)下运行的控制台输出服务器;^TypeError:第一个参数必须是IncomingMessage的ServerResponse.OutgoingMessage.write(http.js:853:11)中的字符串或缓冲区。(/home/overflow/Scrivania/nodewather/app.js:15:13)在IncomingMessage.EventEmitter.emit(events.js:117:20)在_stream_readable.js:920:16在process._tickCallback(node.js:415:13)根据描述的错误文本,您可以推断出问题可能是什么?@marcoferarioli--是的,这是下一个错误。修正这个问题,你就有了最后一个错误。
    var http = require('http');

function getData(city, res,callback){
    var urlData = 'http://api.openweathermap.org/data/2.5/weather?q='+city;

    http.get(urlData, function(resi) {
        var body = '';

        resi.on('data', function(chunk) {
            body += chunk;
        });

        resi.on('end', function() {
            body=JSON.stringify(JSON.parse(body), null, 4)
            res.write(body);
            callback(body);
        });
    }).on('error', function(e) {
          res.write("Got error: " + e);
          callback("error");
    });
}

// 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,function (message) {
            console.log("ad:",message);
            res.end();
        });
    } else { 
        res.write("Use url:port?city=xxxx");
        res.end("done");
    }

}).listen(8124);
console.log('Server running at 8124');