简体   繁体   中英

Cannot read property 'forEach' of undefined in Node.js

I am trying to display selected record and display on the view but am getting this error:

Cannot read property 'forEach' of undefined

I have tried all I could but couldn't resolve it. Please see the code below. I test the connection with the database and it is connected.

router.get('/getme', function(req, res, next) {
 db.query('SELECT * FROM STATE', function (err, rs) {
  res.render('getme', {state: rs});
 });
});


<table>
    <tr>
        <td> state id</td>
        <td> state name </td>
    </tr>
    <% state.forEach(function(item) { %>
    <tr>
        <td><%= item.stateid %></td>
        <td><%= item.state_name %></td>
    </tr>
    <% }); %>
</table>

Connection

var mysql = require('mysql');
var db = mysql.createPool({
host: 'localhost',
user: '',
password: '',
database: 'partme',
debug: false

});
(err, rs)

maybe your rs is undefined and err is not undefined (error when you load from DB)

You should check:

if (err) {
    // handle err here
} else {
    res.render('getme', {state: rs});
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM