I'm trying to change my route dynamically in express for which the exact link is stored in a json file. My json is stored in articles.js looking something like this:
title: 'title1',
link: 'title2',
creator: 'user1',
createdAt: '17/10/2021',
description: 'Test description',
publish: 'True',
text: 'This is a sample text'
},
{
title: 'title2',
link: 'title2',
creator: 'user3',
createdAt: '17/10/2021',
description: 'Test description',
publish: 'True'
},
{
title: 'title3',
link: 'title3',
creator: 'user2',
createdAt: '17/10/2021',
description: 'Test description',
publish: 'True'
}]
exports.articles = articles;
During my get-route I dynamically wnat to render to blog_articles page changing the hyperlink to route \theme\title1, \theme\title2 etc. dynamically. My express routes are defined like this:
const router = express.Router()
const Articles = require('../articles/articles');
router.get("/", async (req, res) => {
const articles = await Object.values(Articles.articles).filter(all => all.publish ==='True');
res.render("theme", {articles: articles});
});
router.get("/:link", async (req, res) => {
var link = req.params.articles.link
const articles = await Object.values(Articles.articles).filter(all => all.publish ==='True');
res.render("blog_articles", {articles: articles.link});
res.send(articles.link);
res.send(req.params.id);
//const articles = await Object.values(Articles.articles).filter(all => all.publish
});
Edit: Here is the theme.ejs:
<!DOCTYPE html>
<html lang="en">
<body>
<div class="container px-4 px-lg-5">
<div class="row gx-4 gx-lg-5 justify-content-center">
<div class="col-md-10 col-lg-8 col-xl-7">
<!-- Post preview-->
<div class="post-preview">
<object data="README.md" type="text/html"></object>
<a href="/index">
<% articles.forEach(article => { %>
<h2 class="post-title" style="margin-bottom: -1.41rem"><a href="futureai/<%=article.link %>", id="Android"><%= article.title %></a></h2>
</a>
<br class="post-gap-title-description" style="margin-bottom: 0.25rem">
<h4 class="post-description" style="font-weight: 300"><%= article.description %></h4>
<p class="post-meta">
Posted by
<a href="#!">
<%= article.creator %>
</a>
on
<a href="#"><%= article.createdAt %></a>
</p>
<hr class="my-4" />
<% }) %>
</div>
<!-- Divider-->
<hr class="my-4" />
<!-- Post preview-->
<!-- Divider-->
<hr class="my-4" />
<!-- Pager-->
<div class="d-flex justify-content-end mb-4"><a class="btn btn-primary text-uppercase" href="#!">Older Posts →</a></div>
</div>
</div>
</div>
</body>
</html>
CodePudding user response:
Use find
to get the article you need:
router.get("/:link", async (req, res) => {
var link = req.params.link
const article = Object.values(Articles.articles)
.filter(all => all.publish ==='True')
.find(article => article.link === link)
res.render("blog_articles", {articles: article.link});
// You have already sent a response, following code is useless
// res.send(articles.link);
// res.send(req.params.id);
});