简体   繁体   中英

How can I get the items in this JSON file to display properly?

So I am not sure what I am doing wrong here. I have these three items from a service and it is in JSON format. When I write out the loop to just display the artist name and the song I keep getting an error

This is the API command in server.js

app.post('/process_form', function(req, res){
    var search = req.body.search
    axios.get('https://itunes.apple.com/search?term='+search)
    .then((response)=>{
        var songlist = response.data.results;
        console.log(songlist);
        res.render('pages/thanks.ejs', {
            songlist: songlist,
            search: search
        });
    });
})

This is the code for the html form where the user can enter the name of a song or artist

        <form action="/process_form" method="post">
            <h1>Which song would you like to lookup</h1>
                <div>
                    <input type="text" id="search" name="search">
                </div>
            <input type="submit">

And this is the form where the results will be output in a list

    <ul>
        <% songlist.forEach(function(songlist) { %>
            <li>
                <strong><%= songlist[artistName] %></strong>
                <strong><%= songlist[TrackName] %></strong>
            </li>
        <% }); %>
    </ul>    

This is what the original source of the data looks like.

 {
    wrapperType: 'track',
    kind: 'song',
    artistId: 216123617,
    collectionId: 982317323,
    trackId: 982317327,
    artistName: 'Rockabye Baby!',
    collectionName: 'Lullaby Renditions of Radiohead',
    trackName: 'Let Down',
  },

Lastly the error I get is that. I am just confused as to why it is saying that I did not define songList

    5|     <main>
    6|         <ul>
 >> 7|             <% songlist.forEach(function(songlist) { %>
    8|                 <li>
    9|                     <strong><%= songlist[artistName] %></strong>
    10|                     <strong><%= songlist[TrackName] %></strong>

songlist is not defined

Sorry for the long post. I am just super frustrated at this and I do not know what I am doing wrong

EDIT: I am using EJS as the view engine

app.set('view engine', 'ejs');

I found the solution was that when was actually rendering my index file, I put

res.render(index)

When the file name was supposed to be

res.render(index.ejs)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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