I have a restAPI backend that I am trying to get data from. I am using NodeJS but for some reason, the data loads in the console as JSON but when I try to print it in the new webpage I get an error
TypeError: /Final part 2/views/pages/letseat.ejs:11
9| </div>
10| <!-- Right here it takes every value that we got back and then puts it into a list item -->
>> 11| <% userlist.forEach(function(userlist) { %>
12| <ul >
13| <input type="checkbox" name=<%= userlist.firstname %>
14| <li ><%= userlist['firstname'] %>, By: <%= userlist['lastname' ]%> </li>
Cannot read properties of undefined (reading 'forEach')
But I do get the data in JSON in the terminal
data: [
{
firstname: 'John',
lastname: 'Boyle',
numberofplaces: null,
user_id: 1
},
{
firstname: 'Ruben',
lastname: 'Holt',
numberofplaces: null,
user_id: 3
},
{
firstname: 'Tim',
lastname: 'Diaz',
numberofplaces: null,
user_id: 4
},
{
firstname: 'Tony',
lastname: 'Santiago',
numberofplaces: null,
user_id: 2
},
{
firstname: 'Scully',
lastname: 'Smith',
numberofplaces: null,
user_id: 5
}
]
The function that I am using to render the page is
<% userlist.forEach(function(songlist) { %>
<ul class="list-group list-group-numbered">
<input type="checkbox" name=<%= userlist.firstname %>
<li class="list-group-item"><%= userlist['firstname'] %>, By: <%= userlist['lastname' ]%> </li>
</ul>
<% }); %>
Lastly this is the API route
app.get('/process_form', function(req, res){
// create a variable to hold the username parsed from the request body
// Now we will use the token wiht the name that the user entered
// For this we will use the axios method to return the result
axios.get('http://127.0.0.1:5000/api/getuser')
.then((response)=>{
var userlist = response.data.results;
console.log(userlist);
res.render('pages/letseat', {
userlist: userlist
});
Please give me some guidance I've been stuck on this for 3 hours!!!
CodePudding user response:
You are trying to access a property that doesn't exist and returning that caused it to be undefined.
var userlist = response.data.results
// ^^^^^^^
response.data
is already an array you wanted. So you gotta change to
var userlist = response.data