2012-06-08 92 views
1

我有一個基本的expressjs應用程序(使用jade),但是我無法渲染基本的Jade文件。當我的請求,我分析的路徑名的URL並使用手柄對象將請求路由如下:在expressjs中渲染jade文件

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; 

家.jade

h1= title 
p Welcome to #{title} 

我使用Jade作爲我的模板引擎,並已配置服務器在一個單獨的server.js文件。當我請求任一頁面時,標題在我的瀏覽器選項卡上正確顯示,但頁面不顯示,只是繼續加載。奇怪的是,當我取消該頁面顯示的請求時。就好像一切正​​常,但沒有任何事情告訴過程結束?

我對節點比較陌生,所以請原諒我對以上任何一條的看法。讓我知道是否有任何問題可以解決。

回答

3

我不是100%肯定的,爲什麼需要以防止超時瀏覽器的代碼不殺TCP連接,但我可以提供一個解決方案,是朝着友好快遞約定應解決您的問題,維護代碼可讀性,可維護性和分離。

./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 
    //  i.e. 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'}) 
    }); 

}); 

上述阻止您需要解析URL參數由你自己。你也可以定義更多可讀和強大的請求處理程序(即POST方法的app.post)。如果您決定構建REST API,現在可以更輕鬆地綁定Express-Resource模塊。

如果您需要更強大的映射,您可以在應用程序的第一個參數使用正則表達式。[GET/POST /把/ DEL]要篩選特定的路徑來代替。