refer to: https://www.udemy.com/course/the-web-developer-bootcamp/
require data.json file:
data.json
{
"soccer": {
"name": "Soccer",
"subscribers": 800000,
"description": "The football subreddit. News, results and discussion about the beautiful game.",
"posts": [
{
"title": "Marten de Roon to make pizza for more than 1,000 people in Bergamo if Atalanta win the Champions league.",
"author": "joeextreme"
},
{
"title": "Stephan Lichtsteiner has retired from professional football",
"author": "odd person"
},
{
"title": "OFFICIAL: Dani Parejo signs for Villareal.",
"author": "joeextreme"
}
]
},
"chickens": {
"name": "Chickens",
"subscribers": 23956,
"description": "A place to post your photos, video and questions about chickens!",
"posts": [
{
"title": "Naughty chicken hid under a shed for 3 weeks and came home with 14 chicks today!",
"author": "joeextreme",
"img": "https://preview.redd.it/sja35au7whd51.jpg?width=640&crop=smart&auto=webp&s=c39f8a99896b55fafc5d0ed882040a963ca54409"
},
{
"title": "Had to kill my first chicken today. Does it get any easier?",
"author": "sad boi"
},
{
"title": "My five year old chicken set and hatched one baby. I guess she wanted to be a mama one more time.",
"author": "tammythetiger",
"img": "https://preview.redd.it/lervkuis3me51.jpg?width=640&crop=smart&auto=webp&s=6a18ab3c4daa80eccf3449217589b922fa443946"
}
]
},
"mightyharvest": {
"name": "Mighty Harvest",
"subscribers": 44002,
"description": "Feeding many villages and village idiots for 10s of days.",
"posts": [
{
"title": "My first meyer lemon ripened today. Im so proud of the little guy. Banana for scale",
"author": "proudmamma",
"img": "https://preview.redd.it/1bz6we4j54941.jpg?width=640&crop=smart&auto=webp&s=a036ea99299f7737efde9f6c3bfa43893f5eaa00"
},
{
"title": "I think I overestimated the harvest basket size I needed.",
"author": "grower123",
"img": "https://preview.redd.it/4h99osd25i351.jpg?width=640&crop=smart&auto=webp&s=d651250a345bbceeba7a66632e8c52a02d71bc73"
}
]
}
}
index.js
const redditData = require('./data.json'); app.get('/r/:subreddit', (req, res) =>{ const{subreddit} = req.params; const data = redditData[subreddit]; if(data){ res.render('subreddit', {...data}); }else{ res.render('notfound', {subreddit}) } })
subreddit.ejs
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title><%= name %> </title> <link rel="stylesheet" href="/app.css"> </head> <body> <h1>Browsing The <%= name %> subreddit</h1> <h2><%= description %></h2> <p><%=subscribers %> Total Subscribers</p> <hr> <% for(let post of posts) { %> <article> <p><%= post.title %> - <b><%=post.author %></b></p> <% if(post.img) { %> <img src="<%= post.img %>" alt=""> <% } %> </article> <% } %> </body> </html>

浙公网安备 33010602011771号