我写了以下代码:
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...");
});我在站点目录中有两个文件:
1. index.html
2. aboutus.html步骤1:我使用节点命令作为节点runServer.js运行上面的代码
步骤2:现在我打开了浏览器并输入了下面的url
http://localhost:8000/浏览器正在正确地向我显示index.html的内容。index.html文件包含一些原始文本并链接到另一个文件,即aboutus.html
Step3:当我单击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
发布于 2013-03-19 09:14:54
我创建了一个静态服务器的示例
看一看@ http://runnable.com/UUgnuT2wDj1UAGSe
var http = require('http');
var fs = require('fs');
var path = require('path');
http.createServer(function (req, res) {
if (req.url === '/') {
req.url = '/index.html';
}
var file = path.join(__dirname,req.url);
path.exists(file, function (exists) {
if (exists) {
fs.stat(file, function (err, stats) {
if(err) {
throw err;
}
if (stats.isFile()) {
res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
fs.createReadStream(file).pipe(res);
} else {
res.writeHead(404);
res.end('not found');
}
});
} else {
res.writeHead(404);
res.end('not found');
}
});
}).listen( 8000 );
console.log('Server running on port ' + 8000);注意:这是使用节点0.6.x的apis,从那时起,fs.exists,而不是path.exists,apis发生了一些变化。
https://stackoverflow.com/questions/15494858
复制相似问题