问题
I have an array of objects I am trying to iterate through in an ejs template, but I keep getting "Reference Error: bills is not defined".
Other StackOverflow questions said to test whether or not the variable was actually defined, so I used
<h1><%= bills.length %></h1>
This properly renders the length of the array, but it still throws an error at
ReferenceError: /index.ejs:11
9| <div id="billCarousel" class="carousel slide" data-ride="carousel">
10| <!--Indicators-->
>> 11| <h1><%= bills.length %></h1>
If I replace this line with
<%= (typeof bills === 'undefined') ? "ERROR" : bills[0].TrackNum %>
Then the TrackNum of the first object is properly rendered, but the error moves to
ReferenceError: index.ejs:13
11| <ol class="carousel-indicators">
12| <%= (typeof bills === 'undefined') ? "ERROR" : bills[0].TrackNum %>
>> 13| <% for (var i=0; i < bills.length; i++) {%>
You can see all of the relevant code below.
pages/index.ejs
<ol class="carousel-indicators">
<h1><%= (typeof bills == 'undefined') ? "ERROR" : bills[0].TrackNum %></h1>
<% for (var i=0; i < bills.length; i++) {%>
<li data-target="#billCarousel" data-slide-to="<%= i %>" class="<%= (i == 0) ? 'active':'' %>"></li>
<% } %>
</ol>
server.js
app.get('/', function(request, response) {
billQuery.summary(function(data) {
console.log(data.bills);
response.render('pages/index', {
page: "index",
status: data.status,
message: data.message,
bills: data.bills
});
})
});
console.log(data.bills) properly prints the array to the console. I have tried rendering status and message in index.ejs, and they work fine. I have already set my Express Engine to EJS with
app.set('view engine', 'ejs');
before I have the route to render index.ejs. I have also restarted my server and cleared my browser's cache several times, but the error keeps occurring. Is there something else I am missing?
回答1:
The issue was because of a 404 error that resulted when the site tried to load the favicon.
app.get('*', function(request, response) {
console.log("Couldn't retrieve "+request.url);
response.render('pages/index', {
page: "index",
status: "Failed",
message: "Error 404"
});
});
When the server attempted to load favicon.ico, it called this route, which seems to delete the bills array which I passed in the "/" route. I put
<link rel="shortcut icon" href="#">
in the head of index.ejs as a temporary fix. Once I changed this route to render a 404 page, the issue was permanently fixed.
来源:https://stackoverflow.com/questions/47385985/ejs-variable-throws-error-even-though-it-renders-properly