【问题标题】:NodeJS res.write doesn't work console worksNodeJS res.write 不工作控制台工作
【发布时间】:2014-08-05 08:28:40
【问题描述】:

我正在尝试使用 Nodejs 创建一个 REST JSON,但是当我尝试编写时,它给了我错误,谁能帮忙?

var oracle = require ( 'oracle' ) ;
var http = require ( 'http' ) ;
var url = require ('url');
var port = 80 ;
var testarray = []; 

var cnnString = {
   hostname        : 'xxx.xxx.xxx.xxx',
   port            : xxxxx,
   database        : 'xxxxxxxxxx.com' ,
   user            : 'xxxxx' ,
   password        : 'xxxxxx'
} ;


oracle.connect ( cnnString, countrylist ) ;


function countrylist( err, connection ) {

   var reader = connection.reader("select distinct company_code, company_name from mbl_employee_v order by company_code", []);

function doRead(cb) {
reader.nextRow(function(err, row) {
    if (err) return cb(err);
    if (row) {
        // do something with row

        testarray.push(JSON.stringify(row));

        return doRead(cb)
    } else {
        // we are done
        return cb();
    }
})
}

doRead(function(err) {
if (err) throw err; // or log it
console.log("all records processed");
 // console.log(testarray);
});
}



var app  = http.createServer ( cb ) ;
app.listen ( port , function () {
console.log ( 'Http server listening at port : ' + port ) ;
} ) ;

function cb ( req, res ) {  
var QueryVal = url.parse(req.url,true);
res.writeHead ( 200 , { 'Content-Type' : 'application/json' } ) ;

switch ( QueryVal.pathname ) {
    case '/' :
        res.write ( "Hello, World" ) ;
        break ;
    case '/about' :

console.log(testarray); 
res.write (testarray) ;

        break ;


    case '/product' :
    res.write ( 'product' ) ;

        break ;         
    default :
        res.write ( 'unknow' ) ;
        break ;
}

res.end ( '' ) ;
} ;

这里我的 console.log 显示了数据,但是 res.write 给了我错误

http.js:851 throw new TypeError('第一个参数必须是字符串或缓冲区'); ^ TypeError: 第一个参数必须是字符串或缓冲区

  • 在 ServerResponse.OutgoingMessage.write (http.js:851:11)
  • 在 Server.cb(/opt/Nodejs/ex05-readData01.js:65:7)
  • 在 Server.emit(events.js:98:17)
  • 在 HTTPParser.parser.onIncoming (http.js:2108:12)
  • 在 HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:121:23)
  • 在 Socket.socket.ondata (http.js:1966:22)
  • 在 TCP.onread (net.js:527:27)

【问题讨论】:

  • res.write(JSON.stringify(testArray)) 告诉我。
  • 你找到解决方案了吗?

标签: javascript node.js


【解决方案1】:

这样做

res.write(JSON.stringify(testArray));

而不是

res.write(testArray);

因为write 函数将 String 或 Buffer 作为参数,而您正在传递一个数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多