Node.js如何呈现视图?

时间:2011-12-31 13:57:12

标签: node.js

在具有单个app.js文件和一个index.html文档的基本Node.js应用程序中,在app.js中指定了以下内容,然后启动服务器并访问{{1}工作得很好:

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中一样。实际上,链接到任何不存在的html页面会将后续页面附加到URL,但会继续显示index.html的内容。

建议将fs.readFile行重写为:

index.html

然后转到fs.readFile(req.url, function(err, page) { ... 加载localhost:8080的内容由于某种原因我不明白。如何呈现这些观点?

2 个答案:

答案 0 :(得分:2)

继续给出其他答案,并建议表达。但首先,对“node.js如何呈现视图?”这一问题的简短回答。是:它没有。

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

或者您可以使用Express等现有框架。以下是使用express的解决方案:

安装快递:

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');

答案 1 :(得分:1)

因为您的请求需要条件才能访问网址(req.url)

现在它关闭了您的第一个res.end()的响应,无论您的网址是什么,并且永远不会到达您的其余代码(确实如此,但响应已经被解雇,因此它没有效果)。

试试这个:

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);