最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Node.js TypeError: Cannot call method 'write' of undefined - Stack Overflow

programmeradmin0浏览0评论

This is the code in nodejs for to call the openweather API and print the result on the 127.0.0.7:8124 but do not understand why it does not work

var http = require('http');

function getData(city, res){
    var urlData = '.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');

this is the error

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 IningMessage.<anonymous> (/home/overflow/Scrivania/nodeweather/app.js:15:13)
    at IningMessage.EventEmitter.emit (events.js:117:20)
    at _stream_readable.js:920:16
    at process._tickCallback (node.js:415:13)
overflow@overflow-1015cx:~/Scrivania/nodeweather$ 

Why can not I return the result?

This is the code in nodejs for to call the openweather API and print the result on the 127.0.0.7:8124 but do not understand why it does not work

var http = require('http');

function getData(city, res){
    var urlData = 'http://api.openweathermap/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');

this is the error

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 IningMessage.<anonymous> (/home/overflow/Scrivania/nodeweather/app.js:15:13)
    at IningMessage.EventEmitter.emit (events.js:117:20)
    at _stream_readable.js:920:16
    at process._tickCallback (node.js:415:13)
overflow@overflow-1015cx:~/Scrivania/nodeweather$ 

Why can not I return the result?

Share Improve this question edited Jul 16, 2014 at 0:11 loganfsmyth 162k31 gold badges346 silver badges258 bronze badges asked Jul 15, 2014 at 23:44 Marco FerraioliMarco Ferraioli 1521 gold badge4 silver badges18 bronze badges 3
  • 2 res or resi? I don't think res means anything. – Michael Lorton Commented Jul 15, 2014 at 23:46
  • "resi" is the variable "res" inside the function getData – Marco Ferraioli Commented Jul 16, 2014 at 5:52
  • I think he's making a mess! – Marco Ferraioli Commented Jul 16, 2014 at 6:09
Add a ment  | 

2 Answers 2

Reset to default 4

You are not passing the response object into getData

I believe it should look like this, but I have not tested it.

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

If you read the error, its not telling you that you can't write, it's saying that you're trying to call write on a null object. If you trace the clues as to how res can be null, it should bee clear.

Nodejs is async, res.end() is called before of res.write inside the http request.. so you need to use some "promise" tecnique or at least callbacks. However this code cannot work since you're trying to write a parsed json string, but the write method accepts only strings or buffer...moreover getData doesn't return nothing..so console.log("ad: "+getData(app,res,res.end)); prints an undefined variable.

maybe this code more fits your idea ( tested and working using "rome" ):

    var http = require('http');

function getData(city, res,callback){
    var urlData = 'http://api.openweathermap/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');
发布评论

评论列表(0)

  1. 暂无评论