Node.js和Express:使用for循环和`app.get()`来提供文章

3
我正在开发一个使用app.get()服务不同网址的node js express应用程序。因此, 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() 运算。

编辑:该网站允许用户提交文章,并在数据库中成为“文章”。我希望这个循环能够路由到已发布的新文章。如果我想对已经启动了node server.js的服务器进行用户提交页面的app.get('/' + newPageName);操作,该怎么做呢?

2个回答

4
利用中间件更好地处理请求。我假设你会有数十/数百篇文章,像你所做的那样为它们添加路由并不够优雅。
考虑以下代码;我正在定义/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');
}

希望这可以帮助您,如有任何问题,请随时询问。

在这种情况下,访问/posts/iPad会带我到那个页面,而/posts/testpage则会抛出“没有这篇文章:testpage”的错误?req.params.leg是指/post/后面的文本吗? - cbsm1th
是的,在应用程序路由中使用:leg来设置req.params中的属性。/posts/a 将呈现 imac 页面,注意 a/b/c 是键。您可以使用任何唯一标识帖子的关键字或 ID,以便从数据库中提取它。 - vmx

2
不,你不应该像那样生成路由处理程序。这就是路由参数的用途。
当你在 Express 路由中以 : 开头的路径组件(文件夹)时,Express 会自动匹配任何遵循该模式的 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();
        }
    });
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接