处理res.json中的null获取

我有一个像这样构build的nodejs应用程序:

app.get('/customer/:ent_cust_id', function (req, res, next) { var query = 'Select * from entcustinfo where ent_cust_id = ' + req.params.ent_cust_id; console.log('Select * from entcustinfo where ent_cust_id =' + req.params.ent_cust_id); client.execute(query, function (err, result) { if (err) return next (err); var row = result.rows[0]; //Response res.json({ent_cust_id: req.params.ent_cust_id, name: row.get('offers')}); }); }); 

但当数组的结果回到空时,会导致节点closures。

 [root@ip-10-205-116-141 cassapi]# /usr/local/bin/node app.js Example app listening at http://0.0.0.0:3030 Select * from entcustinfo where ent_cust_id =1106667844 events.js:87 throw er; // Unhandled 'error' event ^ TypeError: Cannot read property 'get' of undefined at /home/ec2-user/cassapi/app.js:16:14 at readCallback (/home/ec2-user/cassapi/node_modules/cassandra-driver/lib/request-handler.js:195:5) at Connection.invokeCallback (/home/ec2-user/cassapi/node_modules/cassandra-driver/lib/connection.js:567:5) at Connection.handleResult (/home/ec2-user/cassapi/node_modules/cassandra-driver/lib/connection.js:507:8) at ResultEmitter.emit (events.js:120:17) at ResultEmitter.each (/home/ec2-user/cassapi/node_modules/cassandra-driver/lib/streams.js:437:17) at ResultEmitter._write (/home/ec2-user/cassapi/node_modules/cassandra-driver/lib/streams.js:421:10) at doWrite (_stream_writable.js:303:12) at writeOrBuffer (_stream_writable.js:290:5) at ResultEmitter.Writable.write (_stream_writable.js:219:11) 

我试图调整app.get像这样来检查数组是否为空:

 app.get('/customer/:ent_cust_id', function (req, res, next) { var query = 'Select * from entcustinfo where ent_cust_id = ' + req.params.ent_cust_id; console.log('Select * from entcustinfo where ent_cust_id =' + req.params.ent_cust_id); client.execute(query, function (err, result) { if (err) return next (err); var row = result.rows[0]; if (row.get('ent_cust_id') = '') { res.send('ent_cust_id: ' + req.params.ent_cust_id + ' not found. Not all data is loaded.'); } else { var row = result.rows[0]; //Response res.json({ent_cust_id: req.params.ent_cust_id, accts: row.get('accts'), offers: row.get('offers')}); } }); }); 

我想我需要一个if语句来检查result.rows中是否没有logging返回,然后执行res.send。 我试过,但同样的行为仍然发生。 如何找出是否没有logging被返回?

编辑:

在第一部分做了代码更改…粘贴错误的代码…也澄清了问题。

这取决于你的client.execute(sql,callback(err,result))函数的确切行为。 你只需要testing它返回的结果。

如果没有结果,通常来自数据库查询的callback会传递一个空数组。 所以如果你处理result.length == 0的情况,你将不再试图在不存在的行上引用result [i] .row.get。

虽然它不是这个特定问题的原因,但你也想逃避你的SQL查询。 没有任何缺点,它显着增加了您的应用程序的安全性。

我们来攻击这个问题。 首先,你的错误:

 TypeError: Cannot read property 'get' of undefined 

这是告诉你,你写了<object>.get ,但是当它试图访问get属性时,发现<object>undefined

更重要的是,它告诉你它发生了什么:

 /home/ec2-user/cassapi/app.js:16:14 

去那个文件,看看第16行。 这可能是你发布的2个之一:

 app.get('/customer/:ent_cust_id', ...) // or row.get('offers') 

所以,你认为approw是一个get()方法的对象,但其中一个必须是undefined 。 这可能有两个原因:

  • app有一个undefined的值 – 是否分配? 它来自另一个function吗? 这个function是否忘记return
  • 分配给result.rows[0]的行variablesundefinedresult.rows是否有[0]元素? 数组可以是空的吗?

检查您创buildapp对象的部分,以及您从中获取.row[0]results 。 使用console.log来查看它们的值。 错误应该很容易被发现。

 //in your require, consider using below: //var body-parser = require('body-parser'); // after installing with npm. I recommend globally installing //app.use(body-parser()); //make sure you add this to initialize body parser after installing it. *NOTE: If using node with express 4.~ this is deprecated so ignore. app.get('/customer/:ent_cust_id', function (req, res, next) { //Your code: var query = 'Select * from entcustinfo where ent_cust_id = ?' [req.params.ent_cust_id]; /* Above, should probably include a plus sign between "?'" and "[req.params.....]; as below: */ var query = 'Select * from entcustinfo where ent_cust_id = ?' + [req.params.ent_cust_id]; //Another typo detailed below //Your code: consolelog('Select * from entcustinfo where ent_cust_id = ?'); console.log('Select * from entcustinfo where ent_cust_id = ?'); /* Also, at this point you want to be logging your full query var, not your manually entered string value so type this as below: */ console.log(query); // shows your query, not your manually typed string. //There really shouldn't ever be an issue with your manually typed query unless you need it surrounded in quotes. //For greater clarification, whatever you're calling client below should be defined and expanded upon with an example. /* In this code snippet, I typically always send the response first, if there is NOT an err liks so: if(!err){ //do the client's stuff first, else (if there's an error, does not need to be defined) { //do whatever else } Handling errors after it adds a small bit of speed to your process and reduces a step if you get a valid response and leaves error responding to secondary processing under the expectation you won't encounter an error */ client.execute(query, function (err, result) { if(!err) { //do your client stuff first if no error then return next. } else { console.log(err); return next} ; //No conditional needed for the error, because you've gotten here due to your code not working. //if (err) return next (err); var row = result.rows[0]; //Response res.json({ent_cust_id: req.params.ent_cust_id, name: row.get('offers')}); /* Here you're responding with a JSON object as if you were querying a large JSON file. You may want to consider using res.send with and application/json response type. */ }); }); 
 <div> For additional explanation on routing, you may want to look at express documentation here: <a href="http://expressjs.com/4x/api.html#res.json">express res.json</a></div> <p> Also, make sure you're requiring body-parser in node so you can interpret incoming routes! </p> <code> npm install -g body-parser </code>