处理res.json

时间:2015-08-26 00:42:25

标签: javascript node.js

我有一个这样构建的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')});
});
});

但是当数组的结果变回空时它会导致节点关闭......

[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语句来检查results.rows中是否没有返回任何记录,然后执行res.send。我试过了,但同样的行为仍然存在。如何确定是否没有返回记录?

编辑:

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

3 个答案:

答案 0 :(得分:1)

这取决于您的client.execute(sql,callback(err,result))函数的确切行为。你只需要测试它没有结果就会返回什么。

通常,如果没有结果,来自数据库查询的回调将传递一个空数组作为结果。因此,如果您处理result.length == 0的情况,您将不再尝试在不再存在的行上引用result [i] .row.get。

虽然这不是导致此特定问题的原因,但您还希望转义SQL查询。实际上没有任何缺点,它可以显着提高您的应用程序安全性。

答案 1 :(得分:0)

让我们解决这个问题。首先,你的错误:

TypeError: Cannot read property 'get' of undefined

这是node告诉您您已撰写<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 - 是否已分配?它来自另一个功能吗?该功能是否忘记了return
  • 分配给result.rows[0]的行变量为undefinedresult.rows是否有[0]元素?数组可以为空吗?

检查您创建app对象的部分以及您获得的results .row[0]。使用console.log查看其值。错误应该很容易发现。

答案 2 :(得分:0)

&#13;
&#13;
//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.  */
      
});
});
&#13;
<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>
&#13;
&#13;
&#13;