我是節點js的新手。我正在關注該鏈接。但是,這始終執行response.writeHead(404);
所以我不能夠查看的index.html http://thecodinghumanist.com/blog/archives/2011/5/6/serving-static-files-from-node-js基本Web服務器與Node Js發行
這是我的web服務器節點的js代碼。
var http = require('http');
var path = require('path');
var fs = require('fs');
http.createServer(function (request, response) {
console.log('request starting...');
var filePath = "."+request.url;
if (filePath == './')
filePath = '/index.html';
else
console.log(request.url);
var extname = path.extname(filePath);
var contentType = 'text/html';
switch (extname) {
case '.js':
contentType = 'text/javascript';
break;
case '.css':
contentType = 'text/css';
break;
}
fs.exists(filePath, function (exists) {
console.log(filePath);
if (exists) {
fs.readFile(filePath, function (error, content) {
if (error) {
console.log(error);
response.writeHead(500);
response.end();
}
else {
response.writeHead(200, { 'Content-Type': 'text/html' });
response.end(content, 'utf-8');
}
});
}
else {
response.writeHead(404);
response.end();
}
});
}).listen(8125);
我的問題。
- 這不顯示index.html。
- 如何發送基於不同請求的回覆或html文件? 例如:
http://localhost:8125
- > index.htmlhttp://localhost:8125/firstpage.html
- > firstpage.html - 我們是否需要將html文件放在包含server.js(web服務器)的相同目錄中?
我也在cloud9 IDE中嘗試過。
我在SO發現了類似的問題。但我沒有清楚如何解決這個問題。 Node.js - Socket.io client file not being served by basic node web server 在此先感謝。