如何使用 Node.js 构建静态和动态内容混合的页面?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6126584/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:13:33  来源:igfitidea点击:

How to use Node.js to build pages that are a mix between static and dynamic content?

node.js

提问by edt

All pages on my 5 page site should be output using a Node.js server.

我的 5 页站点上的所有页面都应该使用 Node.js 服务器输出。

Most of the page content is static. At the bottom of each page, there is a bit of dynamic content.

大多数页面内容是静态的。在每个页面的底部,都有一些动态内容。

My node.js code currently looks like:

我的 node.js 代码目前看起来像:

var http = require('http'); 

http.createServer(function (request, response) {

    console.log('request starting...');

    response.writeHead(200, { 'Content-Type': 'text/html' });

    var html = '<!DOCTYPE html><html><head><title>My Title</title></head><body>';
    html += 'Some more static content';
    html += 'Some more static content';
    html += 'Some more static content';
    html += 'Some dynamic content';
    html += '</body></html>';

    response.end(html, 'utf-8');

}).listen(38316);

I'm sure there are numerous things wrong about this example. Please enlighten me! For example:

我确信这个例子有很多错误。请赐教!例如:

  • How can I add static content to the page without storing it in a string as a variable value with += numerous times?
  • What is the best practices way to build a small site in Node.js where all pages are a mix between static and dynamic content?
  • 如何将静态内容添加到页面而不将其作为带有 += 的变量值多次存储在字符串中?
  • 在 Node.js 中构建所有页面都是静态和动态内容混合的小型站点的最佳实践方法是什么?

采纳答案by Josh

Personally, I'd use a server that has higher level constructs. For instance, take a look at the expressjs framework - http://expressjs.com/

就个人而言,我会使用具有更高级别构造的服务器。例如,看看 expressjs 框架 - http://expressjs.com/

The constructs you'll be interested in from this package are:

您将从这个包中感兴趣的构造是:

For example in jade:

以玉为例:

!!! 5
html(lang="en")
  head
    title= pageTitle
    script(type='text/javascript')
      if (foo) {
         bar()
      }
  body
    h1 Jade - node template engine
    #container
      - if (youAreUsingJade)
        p You are amazing
      - else
        p Get on it!

Becomes:

变成:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Jade</title>
    <script type="text/javascript">
      if (foo) {
        bar()
      }
    </script>
  </head>
  <body>
    <h1>Jade - node template engine</h1>
    <div id="container">
      <p>You are amazing</p>
    </div>
  </body>
</html>

If you prefer something a little less drasticI would say look at mustache or one of the other engines that looks a bit more like regular-sauce html.

如果您更喜欢不那么激烈的东西,我会说看看 mustache 或其他看起来更像普通酱 html 的引擎之一。

回答by Raynos

Alternative you can just use jsDOM. This means you have a DOM object you can manipulate on the server to add your dynamic content, then you can just flush the DOM as a HTML file / string

或者,您可以只使用jsDOM。这意味着你有一个 DOM 对象,你可以在服务器上操作它来添加你的动态内容,然后你可以将 DOM 作为 HTML 文件/字符串刷新

回答by nponeccop

These days the answer is not so straightforward.

如今,答案并不是那么简单。

If you don't need to be indexed by Google, consider making a single-page application using socket.ioand client-side templates such as jQuery Templates. There are even emerging node.js frameworks for this type of architecture, e.g. socketstream.

如果你不需要由谷歌索引做,可以考虑使用制作单页的应用程序socket.io以及诸如客户端模板jQuery Templates。甚至有针对此类架构的新兴 node.js 框架,例如socketstream.

If you need to be indexed by Google, do you need your dynamic content to be indexed? If yes, consider using expressand server-side templates such as ejs, jadeor mustache. Another (discouraged) approach might be to generate XML from JSON on server and use an XSLT front-end.

如果您需要被 Google 编入索引,您的动态内容是否需要被编入索引?如果是,请考虑使用express服务器端模板,例如ejsjademustache。另一种(不鼓励的)方法可能是从服务器上的 JSON 生成 XML 并使用 XSLT 前端。

If you need only static content to be indexed, consider using expresson server, but don't generate any dynamic HTML on server. Instead, send your dynamic content in JSON format to client using AJAX or socket.io, and render it using client-side templates such as jQuery Templates.

如果您只需要索引静态内容,请考虑express在服务器上使用,但不要在服务器上生成任何动态 HTML。相反,使用 AJAX 或 socket.io 将 JSON 格式的动态内容发送到客户端,并使用客户端模板(如jQuery Templates.

Don't consider server-side DOM: DOM doesn't scale for complex layouts, you will sink in a sea of selectors and DOM calls. Even client-side developers understood that and implemented client-side templates. A new promising approach is weldlibrary. It offers best of both worlds, but it is not mature yet to be used in production (e.g. simple things like conditional rendering are not supported yet).

不要考虑服务器端 DOM:DOM 无法针对复杂的布局进行扩展,您将陷入选择器和 DOM 调用的海洋中。甚至客户端开发人员也理解这一点并实现了客户端模板。一个新的有前途的方法是weld图书馆。它提供了两全其美的优势,但它在生产中的使用还不成熟(例如,尚不支持条件渲染等简单的东西)。

回答by Tamzin Blake

One good way is to use a templating engine. You can store the templates as separate files, and the templating engine has the ability to make the content dynamic. Personally I use yajet (http://www.yajet.net/) which is written for the web but works fine with node, and there are numerous template engines for node on npm.

一种好方法是使用模板引擎。您可以将模板存储为单独的文件,并且模板引擎能够使内容动态化。我个人使用 yajet (http://www.yajet.net/),它是为 Web 编写的,但在 node 上运行良好,并且 npm 上有许多用于 node 的模板引擎。

回答by Addam Driver

One of the best things I found is to use NodeJS, Express and Mustache...

我发现的最好的事情之一是使用 NodeJS、Express 和 Mustache...

You can create your HTML pages as you normally would using Mustache syntax for placeholders for your variables {{name}}...

您可以像往常一样使用 Mustache 语法作为变量 {{name}}...

When a user hits your site, express routs the slug to the correct template... NodeJS get's the file... NodeJS get's the dataset from a DB... Run it through Mustache on the server... Send the completed page to the client...

当用户访问您的站点时,express 会将 slug 路由到正确的模板... NodeJS 获取文件... NodeJS 从 DB 获取数据集...通过服务器上的 Mustache 运行它...将完成的页面发送到客户端...

Here is a scaled back version I wrote on my blog. It's simple but the idea is pretty sound. I use it to quickly deploy pages on my site.

这是我在博客上写的缩小版本。这很简单,但这个想法很合理。我用它在我的网站上快速部署页面。

http://devcrapshoot.com/javascript/nodejs-expressjs-and-mustachejs-template-engine

http://devcrapshoot.com/javascript/nodejs-expressjs-and-mustachejs-template-engine

I went this route because I didn't want to learn all of the extra syntax to write a language I already knew (html). It makes more sense and follows more of a true MVC pattern.

我走这条路是因为我不想学习所有额外的语法来编写我已经知道的语言 (html)。它更有意义,更符合真正的 MVC 模式。

回答by fredtma

A solution have found to this, without using any other modules and or other script is to make the calling script into a module and include it with the function require().
With this solution I can use javascript which ever way I want
What I would do is make an ajax call to a nodejs script (www.example.com/path/script.js)
script.js would need to be built like a module with the exports.functionName=function(){...}
After that include it in your webserver function require(pathToTheScript).functionName(res,req)
You will also need to end the response in the functionName(res,req) by doing res.end();

对此已经找到的解决方案是在不使用任何其他模块和/或其他脚本的情况下将调用脚本制作成一个模块并将其包含在函数中require()
有了这个解决方案,我可以以我想要的任何方式使用 javascript
我要做的是对 nodejs 脚本(www.example.com/path/script.js)进行 ajax 调用,
script.js 需要像模块一样构建在exports.functionName=function(){...}
这之后它包含在你的网络服务器功能require(pathToTheScript).functionName(res,req)
,您还需要通过做res.end()结束在functionName响应(RES,REQ);

回答by Sunil Niranjan

First deliver only static HTML files from server to the client. Then use something like AJAX / server.io to serve the dynamic content. IMO Jade is really ugly for writing HTML code and its better to use a template engine.

首先只将静态 HTML 文件从服务器传送到客户端。然后使用类似 AJAX / server.io 的东西来提供动态内容。IMO Jade 编写 HTML 代码真的很难看,最好使用模板引擎。

I did some Google and found some code by this fellow, its good if you are doing it for PoC / learning.

我做了一些谷歌并找到了这个家伙的一些代码,如果你是为了 PoC/学习而做的,那就太好了。

var server = require('./server'); 
var controller = require("./controller"); 
var urlResponseHandlers = require("./urlResponseHandlers");   

var handle = {};   
handle["/"] = urlResponseHandlers.fetch; 
handle["/fetch"] = urlResponseHandlers.fetch; 
handle["/save"] = urlResponseHandlers.save;   
server.start(controller.dispatch, handle); 

Here is how the logic for handling URLs is displayed -

以下是处理 URL 的逻辑的显示方式 -

var staticHandler = require('./staticHandler');

function dispatch(handler, pathname, req, res) {
  console.log("About to dispatch a request for " + pathname);
  var content = "Hey " + pathname;
  if (typeof handler[pathname] === 'function') {
      content += handler[pathname](req);
      res.writeHead(200, {
          'Content-Type': 'text/html'
      });
      res.write(content);
      res.end();
  } else {
      console.log("No request handler found for " + pathname);
      staticHandler.handleStatic(pathname, res);
  }

}

}

Here is how static files can be handled -

以下是处理静态文件的方法 -

function handleStatic(pageUrl, response) {
    var filename = path.join(process.cwd(), pageUrl);
    path.exists(filename, function (exists) {
        if (!exists) {
            console.log("not exists: " + filename);
            response.writeHead(404, {
                'Content-Type': 'text/html'
            });
            response.write('404 Not Found\n');
            response.end();
            return;
        }
        //Do not send Content type, browser will pick it up. 
        response.writeHead(200);
        var fileStream = fs.createReadStream(filename);
        fileStream.on('end', function () {
            response.end();
        });
        fileStream.pipe(response);
        return;
    });
}
exports.handleStatic = handleStatic;

I liked the idea. All code copied from this link! .

我喜欢这个主意。从此链接复制的所有代码!.