Node.js如何呈现视图?

在一个具有单个app.js文件和一个index.html文件的基本Node.js应用程序中,在app.js中指定了以下内容,然后启动一个服务器并访问localhost:8080就可以了:

 server = http.createServer( function(req, res) { fs.readFile('index.html', function(err, page) { res.writeHead(200, {'Content-Type': 'text/html'}); res.write(page); res.end(); }); fs.readFile('new.html', function(err, page) { res.writeHead(200, {'Content-Type': 'text/html'}); res.write(page); res.end(); }); }); server.listen(8080); 

但是,将index.html复制到其他文件(如new.html并编辑特定内容,然后将链接添加到链接到新页面的index.html ,单击该链接将呈现与index.html相同的内容。 实际上,链接到任何不存在的html页面都会将随后的页面添加到URL中,但不断显示index.html的内容。

在重写fs.readFile行的build议是:

 fs.readFile(req.url, function(err, page) { ... 

然后去localhost:8080加载new.html的内容出于某种原因,我不明白。 应该如何expression这些观点?

因为你需要在你的请求访问URL(req.url)上有条件

现在它closures你的第一个res.end()的响应,不pipe你的url是什么,并且永远不会到达你的代码的其余部分(它的确如此,但是响应已经被触发了,所以它没有任何作用)。

尝试这个:

 server = http.createServer( function(req, res) { if (req.url == '/index.html') { //will be executed only on index.html fs.readFile('index.html', function(err, page) { res.writeHead(200, {'Content-Type': 'text/html'}); res.write(page); res.end(); }); } if (req.url == '/new.html') { //will be executed only for new.html fs.readFile('new.html', function(err, page) { res.writeHead(200, {'Content-Type': 'text/html'}); res.write(page); res.end(); }); } }); server.listen(8080); 

下面给出的其他答案,也build议快递。 但首先,对“node.js如何渲染视图?”这个问题的简短回答。 是:它不。

当您构build节点应用程序时,您正在构build一个小型Web服务器,使用最小的构build块节点可为您提供如http.createServer()。 您需要编写逻辑来select响应请求发送的内容。

或者你可以使用Express等现有的框架。 这里是使用快递的解决scheme:

安装快递:

 npm install express 

然后,在你的app.js中:

 var express = require('express'); var app = express.createServer(); app.get('/index.html', function(req,res) { res.render('index.html'); }); app.get('/new.html', function(req,res) { res.render('new.html'); }); app.listen(8080) 

您也可以使用EJS或Jade作为模板语言,在createServer行之前添加:

 app.set('view engine', 'ejs'); 

要么:

 app.set('view engine', 'jade');