【问题标题】:TypeError: Cannot read property 'length' of undefined?TypeError:无法读取未定义的属性“长度”?
【发布时间】:2016-01-10 22:50:19
【问题描述】:

我收到“TypeError:无法读取未定义的属性‘长度’?”错误,当我尝试从保存在文件中的联系人中获取特定联系人(提供电话号码)时。

exports.query = function(number) {
   var json_result = JSON.parse(read_json_file());
   console.log(json_result);
   var result = json_result.result;
   for (var i = 0; i < result.length; i++) {
      var contact = result[i];
      if (contact.primarycontactnumber === number)    {
         return contact;
      }
   }
   return null;
};

我将上面的代码称为:

  app.get('/contacts/:number', function(request, response) {
   response.setHeader('content-type', 'application/json');
   response.end(JSON.stringify(contacts.query(request.params.number)));
 });

我的 read_json_file 方法的代码是:

function read_json_file() {
   var file = './data/contacts.json';
   return fs.readFileSync(file);
}

【问题讨论】:

  • json_result 登录到控制台时的内容是什么?

标签: node.js rest express


【解决方案1】:

我想json_result 没有属性result。如果它符合您的功能逻辑,您可以像这样防御性地设置result 变量:

var result = json_result.result || [];

如果json_result.result 未定义(或评估为假),什么会将空数组分配给result 变量。

【讨论】:

    猜你喜欢
    • 2020-06-12
    • 1970-01-01
    • 2021-12-05
    • 2020-07-20
    • 2020-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多