2015-11-05 68 views
-1

我怎樣才能得到我的應用程序的客戶端的index.html?Index.html而不是客戶端的東西在服務器端

索引頁在server.js像這樣定義

// load css styles 
var css = '<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> '; 
css = css + '<style type="text/css">' +require('fs').readFileSync('./style.css').toString() + '</style>' 

http.createServer(function (req, res) { 
    // send basic http headers to client 
    res.writeHead(200, { 
     "Content-Type": "text/html", 
     "Transfer-Encoding": "chunked" 
    }); 
    // setup simple html page: 
    res.write("<html>\n<head>\n<title>Newsfeed</title>\n" +css +"</head>\n<body>"); 

但我想獲得一個index.html這樣我就可以使用純HTML的前端。

+0

這太大了,不能很好地回答這個問題,但是你需要編寫單獨的前端和後端。我更喜歡使用REST API將兩者結合在一起,但將它們保存在單獨的項目中(使用第三個共享庫)。 – ssube

+2

你已經用[express](http://stackoverflow.com/questions/tagged/express)標記了這個,所以不能回答你的問題嗎? –

回答

0

這會解釋長。 簡單的答案是,你分開看法,並使用快遞middlewer進行路由。

您必須設置視圖位置:

app.set('views', __dirname + '/yourViewDirectory'); 

把你的index.html爲/views文件夾

然後你可以使用res.render功能:

res.render('index.html'); 

這是基本Express服務器,其中渲染index.htmllocalhost:3000/

var express = require('express'); 
var app = express(); 

app.set('views', __dirname + '/yourViewDirectory'); 
app.get('/', function (req, res) { 
    res.render('index.html'); 
}); 

var server = app.listen(3000, function() { 
    var host = server.address().address; 
    var port = server.address().port; 

    console.log('Example app listening at http://%s:%s', host, port); 
});