I am trying to send data from my nodejs server with ejs to my html. But the problem is I cant read the variable inside my 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 inside my html with smth like this:
var events = <%= events %>
but I get console error that events doesn’t exist. Any idea how can I fix this or how can I make it work different way?
I tried creating div and direct assigning but it didn’t worked.
2
Answers
Just to update this issue, I found solution that works for me.
You seem to be passing
events
correctly to your ejs views by usingres.render
so if you are confident thatevents
is populated and that you don’t have any database errors then the objects in yourevents
array can be accessed like so: