In a basic Node.js application with a single app.js file and one index.html document where in app.js the following is specified, then firing up a server and visiting localhost:8080 works just fine:
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);
However, when duplicating index.html to another file like new.html and editing certain content, then adding an link into index.html linking to the new page, clicking on the link will render the same content as in index.html. In fact, linking to any non-existent html page will append the subsequent page to the URL but keep showing index.html‘s contents.
Following a suggestion of rewriting the fs.readFile line to be:
fs.readFile(req.url, function(err, page) { ...
Then going to localhost:8080 loads new.html‘s contents for some reason I don’t understand. How should one render out these views?
Because you need to have conditions on your request access url (req.url).
Right now it closes the response on your first
res.end()regardless of your url, and never reach the rest of your code (well it does but the response already fired before so it has no effect).try this: