2015-08-27 220 views
0
var http = require('http'), 
fs=require('fs'), 
path=require('path'), 
host ='127.0.0.1', 
port='9001'; 
var mimes = { 
    ".htm":"text/html", 
    ".css":"text/css", 
    ".js":"text/javascript", 
    ".gif":"text/gif", 
    ".jpg":"text/jpeg", 
    ".png":"text/png" 
} 
var server = http.createServer(function(req,res){ 
    var filepath =(req.url==='/')?('./index.htm'):('.'+req.url); 
    var contentType = mimes[path.extname(filepath)]; 
    //check file exists or not 
    fs.exists(filepath,function(file_exists){ 
     if(file_exists) 
     { 
       res.writeHead(200, {'Content-Type' : contentType}); 
       var streamFile = fs.createReadStream(filepath).pipe(res); 
       streamFile.on('error',function(){ 
        res.writeHead(500); 
        res.end(); 
       }) 
     } 
     else 
     { 
      res.writeHead(404); 
      res.end("sorry we could not find the file you requested"); 
     } 
    }) 
}).listen(port,host,function(){ 
console.log('server running on http://'+host+':'+port); 
}) 

在上面的代碼我的節點服務器所賜消息中127.0.0.1:9001它的運行,但是當我在瀏覽器中運行它,我遇到「錯誤404文件未找到」 ,這不是我提到的錯誤。此外,我在這個腳本文件的同一個文件夾中有index.html文件。我的代碼有什麼問題?Node.js的404文件未找到錯誤

回答

0

你的代碼爲我工作得很好。 你應該有index.htm文件在同一文件夾您執行server.js文件。

更改,如果條件

index.html != index.htm 
+0

非常感謝Mahesh :)它解決了。非常感謝 –

2

其實你的代碼做工精細,

你可能會改變你的404

res.writeHead(404, {"Content-Type": "text/plain"}); 
    res.end("sorry we could not find the file you requested"); 

也看到,我們已經設置了響應類型爲 'text/html的'

http://nodejs.org/api/http.html#http_class_http_serverresponse

enter image description here

+1

感謝您的建議,但我不知道爲什麼它不讀我的靜態index.html文件。 –