简体   繁体   English

如何在Express.js中定义单个页面

[英]How do I define individual pages in Express.js

I'm just getting started with express.js and am failing to understand how one defines discrete "pages" (in the traditional sense) that one can link to internally. 我刚刚开始使用express.js ,却无法理解一个人如何定义一个可以在内部链接到的离散“页面”(按传统意义)。

I'm using Jade as a template engine and I see how it pulls the various components together and references them in the app.js (which is what is initially invoked by npm) so that, in effect is my "index". 我使用Jade作为模板引擎,我看到它如何将各种组件组合在一起并在app.js中引用它们(这是npm最初调用的内容),因此实际上就是我的“索引”。 Would be great to see a tutorial on what one does to then build out pageA, pageB, pageC so that they can be linked to via <a href="pageA.html"> (or the Jade equivalent). 很高兴看到有关如何构建pageA,pageB,pageC的教程,以便可以通过<a href="pageA.html"> (或等效的Jade)将它们链接到。

I'm assuming this is possible, right? 我以为这是可能的,对吧?

Express.js itself does not offer URL generation, only a built-in router. Express.js本身不提供URL生成,仅提供内置路由器。

You would need to use an additional package to perform URL generation, or build it yourself. 您将需要使用其他程序包来执行URL生成,或者自己构建。 Maybe you find something fitting in this question's answers: URL generation for routes in express 也许您在此问题的答案中找到了合适的方法: express路线的URL生成

If you do not care about route generation and want to "hard code" the URLs, you would need to add a route for each static page, like this: 如果您不关心路由的生成,并且想“硬编码” URL,则需要为每个静态页面添加一条路由 ,如下所示:

// routes.js
app.get("/pageA.html", function(req, res, next) { res.render("static/page_a", { templateLocals: "here" }) };
app.get("/pageB.html", function(req, res, next) { res.render("static/page_b") };

Or, if you have many of those pages, you could use a controller for this: 或者,如果您有许多页面,则可以为此使用控制器

// static_page_controller.js
module.exports = function(pageTemplate) {
  return function(req, res, next) {
    return res.render("static/" + pageTemplate);
  }
}

And use it like this: 并像这样使用它:

// routes.js
var staticController = require("./static_page_controller");

app.get("/pageA.html", staticController("page_a"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM