首页 > 解决方案 > 获取 TypeError:无法读取属性未定义的

问题描述

当我尝试访问我在后端创建的 JSON 文件时收到此错误。所以我使用 Node.js 作为我的中间件来访问我的 react js 中的数据库,它会发回一个 JSON 响应。后端部分(FetchDB.js):

routing.get('/viewTableData', function(req, res, next)
{
  pool.connect(function (err, client, done)
  {
    if(err)
    {
      console.log("Can't connect to DB"+err);
    }
    client.query('SELET * from MyTable', function(err, result)
                  {
                    done();
                    if(err)
                    {
                      console.log(err);
                      res.status(400).send(err);
                    }
                    var toSend = {rows:[]};
                    toSend["rows"] = result.rows;
                    res.status(200).send(toSend); 
                 })
         })
})  

请参阅我遇到问题的 ViewList.js 的注释(第 1 行和第 2 行)。在第 1 行中,它以 json 格式向我显示了预期的确切数据。但是,当我尝试访问 json 文件的键时,出现上述错误。当我对this.state.list使用 typeof时,我会在控制台中获得对象,并为this.state.val.rows[0].createdDate 获得undefined。在 Postman 中观察到的 json 响应如下:

{
  "rows": [
    {
      "createdDate": "cr_date1",
      "lastModifiedDate": "mod_date1",
      "jsonData": "some_data_1_is_here"
    },
    {
      "createdDate": "cr_date_2",
      "lastModifiedDate": "mod_date_2",
      "jsonData": "some_data_2_is_here"
    },
    {
      "createdDate": "cr_date_3",
      "lastModifiedDate": "mod_date_3",
      "jsonData": "some_data_3_is_here"
    }
}

ViewList.js:

import React, { Component } from 'react';
import axios from 'axios';

export default class ViewList extends Component {

  constructor(props)
  {
    super(props);
    this.state = {
      val: {
        "rows" : []
        }
      }
    this.callMe = this.callMe.bind(this);
  }

  callMe()
  {   

    axios.get('http://localhost:4321/viewTableData')
    .then(res => {
        this.setState({
          val: res.data,
        })
      })

  }

  componentDidMount()
  {
    this.callMe();
  }

  render()
  {

    console.log(this.state.val);                                          // line 1
    console.log(this.state.val.rows[1].createdDate);                      // line 2

    return (
        <p>some text here</p>
      )
  }
}

标签: node.jsjsonreactjsaxios

解决方案


正如 Dale Coms 所提到的,您的 SELECT 语句中有一个错字,这可能会导致数据库服务器的响应为空,因此没有 JSON 可以转发。

您正在在线编写 SELET 而不是 SELECT

client.query('SELET * from MyTable', function(err, result).

它应该是:

client.query('SELECT * from MyTable', function(err, result).


推荐阅读