I'm trying to use Nodejs to create a REST JSON but when I try to write, it gives me error can anyone help?
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 ( '' ) ;
} ;
here my console.log shows the data, but the res.write gives me error
http.js:851 throw new TypeError('first argument must be a string or Buffer'); ^ TypeError: first argument must be a string or Buffer
- at ServerResponse.OutgoingMessage.write (http.js:851:11)
- at Server.cb(/opt/Nodejs/ex05-readData01.js:65:7)
- at Server.emit(events.js:98:17)
- at HTTPParser.parser.onIncoming (http.js:2108:12)
- at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:121:23)
- at Socket.socket.ondata (http.js:1966:22)
- at TCP.onread (net.js:527:27)
Do this
res.write(JSON.stringify(testArray));
instead of
res.write(testArray);
because write
function takes a String or Buffer as argument, and you are passing an array.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.