NodeJS uses ejs to send data to <script>
P粉511757848
P粉511757848 2023-09-07 15:08:05
0
1
745

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粉511757848
P粉511757848

reply all(1)
P粉891237912

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>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template