以expressjs渲染玉文件

我有一个基本的expressjs应用程序(使用翡翠),但我无法呈现基本的Jade文件。 当我得到一个请求,我parsingpath名的URL,并使用句柄对象路由请求,如下所示:

index.js

var requestHandlers = require('./requestHandlers'); var handle = {}; handle['/'] = requestHandlers.start; handle['/download'] = requestHandlers.download 

requestHandlers.js

  function start(res) { console.log("request handler for start called"); res.render('home', {title: 'express'}); } function download(res) { res.render('download', {title: 'download'}) res.end(); } exports.start = start; exports.download = download; 

home.jade

 h1= title p Welcome to #{title} 

我使用Jade作为模板引擎,并将服务器configuration为独立的server.js文件。 当我请求任何页面时,标题显示在我的浏览器选项卡上,但页面不显示,它只是不断加载。 奇怪的是,当我取消请求的页面显示。 就好像一切正​​常,但没有任何事情告诉过程结束?

我对节点相对来说比较陌生,所以对于上述任何一点,我都很无奈。 如果有任何问题我可以澄清,让我知道。

我不是100%正面的,为什么你的代码没有根据需要查杀TCP连接,以防止你的浏览器超时,但是我可以提供一个对Express约定友好的解决scheme,它可以解决你的问题并保持代码的可读性,可维护性和分离。

./app.js(你的主服务器脚本)

 var express = require('express'), app = express.createServer(), routes = require('./routes'); app.configure(function () { // Render .jade files found in the ./views folder // I believe you are already doing this app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); // Use the built-in Express router // This kills the "handle" method you had implemented app.use(app.router); // Client-side assets will be served from a separate ./public folder // ie http://yourhost.com/js/main.js will link to ./public/js/main.js app.use(express.static(__dirname + '/public')); }); // Initialize routes routes.init(app); 

./routes/index.js

 exports.init = function (app) { app.get('/', function (req, res) { console.log("request handler for start called"); // Render __dirname/views/home.jade res.render('home', {title: 'express'}); }); app.get('/download', function (req, res) { // Render __dirname/views/download.jade res.render('download', {title: 'download'}) }); }); 

以上防止您需要自己parsingURL参数。 你也可以定义更可读和更强大的请求处理程序(例如POST方法的app.post)。 如果您决定构buildREST API,现在可以更轻松地绑定Express-Resource模块。

如果你需要更强大的映射,你可以在应用的第一个参数[get / post / put / del]中使用正则expression式来过滤特定的path。