簡體   English   中英

Node.js TypeError:無法調用未定義的方法“寫入”

[英]Node.js TypeError: Cannot call method 'write' of undefined

這是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$ 

為什么我不能返回結果?

您沒有將響應對象傳遞給getData

我相信它應該看起來像這樣,但我尚未對其進行測試。

 if(app){
        console.log("ad: "+getData(app,res));
    } else res.write("Use url:port?city=xxxx");\

如果您讀取該錯誤,它並沒有告訴您不能編寫,而是您正在嘗試對null對象調用write。 如果您找到關於res可以為null的線索,那么它應該很清楚。

Node.js是異步的,在HTTP請求中在res.write之前先調用res.end(),因此您需要使用一些“承諾”技術或至少使用回調。 但是,由於您嘗試編寫已解析的json字符串,因此該代碼無法正常工作,但是write方法僅接受字符串或緩沖區...此外,getData不會返回任何內容。.soconsole.log(“ ad:” + getData(應用程序,RES,res.end)); 打印一個未定義的變量。

也許這段代碼更符合您的想法(經過測試並使用“ rome”進行工作):

    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');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM