无法读取未定义的属性“ length”(角度6)

时间:2020-03-24 14:50:40

标签: mysql node.js angular express

我正在尝试在我的项目中显示MySQL表,该项目现在正在从本地json文件中获取表。

public getProperties(): Observable<Property[]>{
    return this.http.get<Property[]>(this.url + 'properties.json');

  }

当用我使用NodeJs获取mysql表对象并表达的URL替换URL时,在控制台中出现给定的错误。这是我去的方式:

public getProperties(): Observable<Property[]>{
    return this.http.get<Property[]>('http://localhost:3000/');

  }

有没有一种方法可以成功地传递URL来访问MySQL表?

这是我的NodeJS代码:

router.get('/', function(req, res, next) {
  res.setHeader("Content-Type", "text/html");

  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  console.log("Function called")
  con.query('SELECT * FROM authors', (err,rows) => {
    if(err) throw err;

    console.log('Data received from Db:');
    console.log(rows);
    DBRows = rows;

    console.log("Data sent")
    res.send(JSON.stringify(DBRows));
  });
});

  con.query('SELECT * FROM authors', (err,rows) => {
    if(err) throw err;

    console.log('Data received from Db:');
    console.log(rows);
    DBRows = rows;

    console.log("Data sent")
    JSON.stringify(DBRows);
    res.send(JSON.stringify(DBRows));

  });

});

1 个答案:

答案 0 :(得分:0)

“ JSON.stringify(DBRows)”的结果是什么?

您期望结果(Property [])中有一个Property数组,但是您返回了一个字符串化的DBRows,它可能是一个对象

您需要修改代码,以使结果与您期望的相符。 如果“ JSON.stringify(DBRows)”的结果为

{
   values: [ {/* DbRow */}, {/* DbRow */}, ... ]
}

然后在您的服务中,您需要一个类似的对象,例如:

export class Response {
   values: Property[];
}
...
return this.http.get<Response>('http://localhost:3000/');