【问题标题】:Router for nodejsnodejs的路由器
【发布时间】:2014-04-14 18:17:12
【问题描述】:

服务器 nodejs + express 有很多教程。您可以简单地编写 res.render(somefile) 并快速显示 html 页面。但是如何在普通的nodejs中做到这一点,如何渲染页面? 我在http://www.nodebeginner.org/找不到答案

我编写了简单的服务器,但不知道如何根据需要修复它:

var http = require("http");
var url = require("url");
var fs = require("fs");



function onRequest(request, response) {
    var pathname = url.parse(request.url).pathname;
    var filename = 'gallery/index.html';
    fs.readFile(filename, function(err, file) {
        if(err) {
            response.writeHead(500, {"Content-Type": "text/plain"});
            response.write(err + "\n");
            response.close();
            return;
        }

        response.writeHead(200, {"Content-Type": "text/html"});
        response.write(file);
        response.end();
    });
}

    http.createServer(onRequest).listen(8888);
    console.log("Server has started.");

这段代码只是渲染一个页面-gallery/index.html,但是渲染它没有图像因为找不到它们,但是如何渲染目录?例如,我想在我的画廊目录中查看 index.html,如果我写 http://localhost:8888/gallery/,则在 apache 中 - 我将从目录“画廊”接收 index.html 页面,如何在 node.js 中制作相同的页面?

更新:我用 node-static 模块解决了我的问题,这个答案对我很有帮助https://stackoverflow.com/a/6162856/2560165

【问题讨论】:

  • 如果您想实现自己的静态服务器,Connect Static 是一个很好的参考。
  • 如果你想自己动手,这是一个好的开始:gist.github.com/hectorcorrea/2573391 但从长远来看,我会使用 Connect Static 或其他已构建的模块。

标签: node.js


【解决方案1】:

我认为你需要在 http://expressjs.com/ 框架上抢购一下,尤其是路由器代码 - https://github.com/visionmedia/express/tree/master/lib/router

【讨论】:

    【解决方案2】:

    当调用res.render(somefile) 时,express 的作用是渲染一个 HTML 模板文件(默认为 Jade)。查看views 文件夹,您会在其中找到*.jade 模板文件。

    如果你想自己做,你只需要想出一个包含很多占位符的模板:

    <html>
      <head/>
      <body>
        <h1>Hello {name}</h1>
      </body>
    </html>
    

    然后用实际值替换占位符(在本例中为 {name})。

    【讨论】:

      【解决方案3】:

      我用 node-static 模块解决了我的问题,这个答案对我来说非常有用https://stackoverflow.com/a/6162856/2560165

      【讨论】:

        猜你喜欢
        • 2018-09-27
        • 2017-03-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-16
        • 2018-04-22
        相关资源
        最近更新 更多