gpt4 book ai didi

javascript - 在 Node Express 应用程序中设置通用路由。 (网址/索引、网址/索引2、网址/索引3...)

转载 作者:太空宇宙 更新时间:2023-11-03 23:50:35 28 4
gpt4 key购买 nike

我正在通过 NodeSchool.io 练习学习 React 和 Express 框架。
我想将所有练习文件存储在具有多个页面的单个应用程序中,例如

索引
索引2
索引3
索引4
....

localhost:3000/indexN

但我无法为此类 URL 设置路由。项目仓库:Git Public Repo URL

尝试了各种方法但无法解决问题。
How to configure dynamic routes with express.js

app.use("/indexn*", function(req, res) {
res.render("indexn", "");
});

API 类型的解决方案的工作原理如下,但这也没有帮助,因为它的参数化 URL

 // http://localhost:3000/index/2
app.get('/index/:id', function(req , res){
res.render('index' + req.params.id, "");
});

我还在上面的函数中尝试了各种正则表达式模式,例如
(索引)n,索引:n*
但编译失败。

感谢您的帮助。

最佳答案

您可以按照正确的语法使用正则表达式(不带引号,但使用 /delimiters/):

app.use(/\/index.*/, function(req, res) {
// code
});

这将匹配任何以“/index”开头的路径。要仅匹配“/index”后跟数字 n,请使用以下模式:/\/index[0-9]*/

您还可以使用类似 glob 的模式来匹配文件路径:'/index*'

您可以通过检查 req 对象来根据请求的实际路径来处理请求。

app.use('/index*', function(req, res) {
res.render(req.originalUrl);
});

比照。 app.use() documentation

关于javascript - 在 Node Express 应用程序中设置通用路由。 (网址/索引、网址/索引2、网址/索引3...),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59633550/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com