繁体   English   中英

为什么显示 function 未定义? 它确实在控制台中记录结果,我只是想列出名字

[英]Why is it showing that the function is not defined? It does log the results in console, I am just trying to list the first name

我有一个试图从中获取数据的 restAPI 后端。 我正在使用 NodeJS,但由于某种原因,数据在控制台中加载为 JSON 但是当我尝试在新网页中打印它时出现错误

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 class="list-group list-group-numbered">
    13|                     <input type="checkbox" name=<%= userlist.firstname %>
    14|                     <li class="list-group-item"><%= userlist['firstname'] %>, By: <%= userlist['lastname' ]%> </li>

Cannot read properties of undefined (reading 'forEach')

但我确实在终端中获得了 JSON 中的数据

  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
    }
  ]

我用来呈现页面的 function 是

    <% 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>
    <% }); %>  

最后这是 API 路线

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
        });

请给我一些指导,我已经坚持了3个小时!!!

您正在尝试访问一个不存在的属性并返回导致它未定义的属性。

    var userlist = response.data.results
//                               ^^^^^^^

response.data已经是您想要的数组。 所以你必须改为

    var userlist = response.data

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM