I'm trying to use ejs to send data from my Nodejs server to my html. But the problem is that I can't read the variables in the script.
Nodejs server:
exports.getIndex = (req, res, next) => { var alert = req.query.msg; // connect to your database mssql.connect(config, function (err) { if (err) console.log(err); var request = new mssql.Request(); request.query( "SELECT startDate, endDate from Reservations", function (err, recordset) { if (err) console.log(err); events = []; recordset.recordset.forEach((element) => { reserv = {}; reserv.start = element.startDate; reserv.end = element.endDate; events.push(reserv); }); res.render("index", { alert: alert, events: events, }); } ); }); };
I need to read events in html like this:
var events = <%= events %>
But I get a console error stating that the event does not exist. Any idea how to fix this or how to make it work differently?
I tried creating the div and assigning it directly, but without success.
P粉8912379122023-09-08 13:03:03
You appear to be using res.render
to correctly pass events
to your ejs view, so if you are sure that events
is populated and if you don't have any Database error, you can access the objects in the events
array like this:
<ul> <% events.forEach(function(event) { %> <li> Start: <%= event.start %> | End: <%= event.end %> </li> <% }); %> </ul>