我已经写下面的代码:节点和路由管理
var http = require('http');
var fs = require('fs');
var fileName = 'site/index.html';
var encoding = 'utf-8';
var dataContent = "";
fs.readFile(fileName, encoding, function(error, data) {
if(error) throw error;
dataContent = data;
});
var requestListener = function(request, response) {
response.writeHead(200, {
'Content-Length': dataContent.length,
'Content-Type': 'text/html',
'connection': 'keep-alive',
'accept': '*/*'
});
response.end(dataContent);
}
var server = http.createServer(requestListener, function(connect) {
connect.on('end', function() {
console.log('Server disconnected...');
});
});
server.listen(8000, function() {
console.log("Server is listening...");
});
我有2个文件中的网站目录:
1. index.html
2. aboutus.html
步骤1:我使用节点命令作为节点RUNSERVER运行上面的代码。 JS
第2步:现在我已经打开浏览器和类型以下网址
http://localhost:8000/
浏览器正确显示了index.html的内容。 而index.html文件内容,一些原始的文字和链接,即aboutus.html
第三步另一个文件:当我点击点击链接aboutus.html浏览器更改URL为以下
http://localhost:8000/aboutus.html
但aboutus.html的内容不显示,而是它显示我的内容index.html
我知道这是因为fileName变量内容'site/index.html'发生。所以浏览器正在渲染index.html内容
我该如何改变这种行为?如果我不使用express.js
现在,我做了下面的代码一些变化:
var http = require('http');
var fs = require('fs');
var path = require('path');
var fileName = "site/index.html";
var encoding = 'utf-8';
var dataContent = "";
function readContentFile(fileName) {
console.log(fileName);
fs.readFile(fileName, encoding, function(error, data) {
if(error) throw error;
dataContent = data;
});
}
readContentFile(fileName);
var requestListener = function(request, response) {
filePath = request.url;
if(filePath!='/') {
fileName = 'site' + filePath;
readContentFile(fileName);
}
response.writeHead(200, {
'Content-Length': dataContent.length,
'Content-Type': 'text/html',
'connection': 'keep-alive',
'accept': '*/*'
});
response.end(dataContent);
}
var server = http.createServer(requestListener, function(connect) {
connect.on('end', function() {
console.log('Server disconnected...');
});
});
server.listen(8000, function() {
console.log("Server is listening...");
});
不过其没有工作,是什么东西错在我的代码。 或者我应该去express.js
任何特殊原因不使用Express? – robertklep 2013-03-19 09:01:53
我是新node.js 所以,我正在考虑不使用express.js – 2013-03-19 09:05:34
我刚开始使用时,我开始使用的第一个框架之一是快递:) – robertklep 2013-03-19 09:09:07