![](/img/trans.png)
[英]Node.js & Express: How to create many app.get calls with Express.js through “for loop”?
[英]node.js & express: for loop and `app.get()` to serve articles
我正在开发一个节点js express应用程序,它使用app.get()来提供不同的Web地址。 所以app.get('/',{});
提供主页app.get('/login'{ });
提供登录页面等
使用for循环以编程方式提供页面是不错的做法,就像在这个例子中一样?
var a = ["a", "b", "c"];
a.forEach(function(leg) {
app.get('/' + leg, function(req, res){
res.render('index.ejs', {
word : leg
});
});
});
index.ejs
只是<p><%= word %> </p>
因此site.com/a,site.com/b和site.com/c都是网页。
我想利用它在所有文章标题列表中运行.foreach()(来自存储文章的数据库)。
编辑:该网站允许用户提交帖子,这些帖子成为数据库中的“文章”。 我希望这个循环在发布之后路由到新提交的文章。 如果我想做app.get('/' + newPageName);
用户提交的页面在我用服务器node server.js
启动服务器后,如何实现?
利用中间件来更好地处理请求。 我假设你会有几十个/几百个帖子,为你们添加路线就像你们所做的一样,并不那么优雅。
考虑以下代码; 我正在定义/posts/:legId
表单的路由。 我们将匹配此路由的所有请求,获取文章并进行渲染。
如果要定义少量路由,则可以使用正则表达式来定义它们。
// dummy legs
var legs = {
a: 'iMac',
b: 'iPhone',
c: 'iPad'
};
app.get('/posts/:leg', fetch, render, errors);
function fetch(req, res, next) {
var legId = req.params.leg;
// add code to fetch articles here
var err;
if (!legs[legId]) {
err = new Error('no such article: ' + legId);
}
req.leg = legs[legId];
next(err);
}
function render(req, res, next) {
res.locals.word = req.leg;
res.render('index');
}
function errors(err, req, res, next) {
console.log(err);
res.locals.error = err.message;
// render an error/404 page
res.render('error');
}
希望这有帮助,随时问我任何问题。
不,你不应该像这样生成路由处理程序。 这是路由参数的用途。
当你开始一个路径组件(文件夹) :
在快速路,快速将匹配自动跟随模式中的任何URL,然后将实际值req.params
。 例如:
app.get('/posts/:leg', function(req, res, next) {
// This will match any URL of the form /post/something
// -- but NOT /post/something/else
if (/* the value of req.params.leg is valid */) {
res.render('index.ejs', { word: req.params.leg });
} else {
next(); // Since the user requested a post we don't know about, don't do
// anything -- just pass the request off to the next handler
// function. If no handler responds to the request, Express
// defaults to sending a 404.
}
});
在现实世界中,您可能通过执行数据库查找来确定leg
参数是否有效,这需要进行异步调用:
app.get('/posts/:leg', function(req, res, next) {
db.query(..., req.params.leg, function(err, result) {
if (err) next(err); // Something went wrong with the database, so we pass
// the error up the chain. By default, Express will
// return a 500 to the user.
else {
if (result) res.render('index.ejs', result);
else next();
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.