通过从json文件中提取路由路径,在express中动态更改路由



我正在尝试用express动态更改我的路由,它的确切链接存储在json文件中。我的json存储在articles.js中,看起来像这样:

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;

在我的get-route过程中,我动态地拥有呈现到blog_articles页面的权限,动态地将超链接更改为route\them\title1\theme\title2等。我的快递路线是这样定义的:

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

编辑:这是主题。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>

使用find获取您需要的文章:

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

最新更新