2016-08-16 5 views
-1

私は以下のserver.jsコードを書いた:なぜ私は404ページが見つかりませんにリダイレクトされていますか?

// Require modules 
const http = require('http'); 

const url = require('url'); 
const path = require('path'); 
const fs = require('fs'); 

// Array of Mime Types 
const mimeTypes = { 
    "html" : "text/html", 
    "jpeg" : "image/jpeg", 
    "jpg" : "image/jpeg", 
    "png" : "image/png", 
    "js" : "text/javascript", 
    "css" : "text/css" 
}; 

// Create Server 
const server = http.createServer(function(req, res){ 
    const uri = url.parse(req.url).pathname; 
    const fileName = path.join(process.cwd(),unescape(uri)); 
    console.log('Loading '+ uri); 
    const stats; 

    try{ 
     stats = fs.lstatSync(filename); 
    } catch(e) { 
     res.writeHead(404, {'Content-type': 'text/plain'}); 
     res.write('404 Not Found\n'); 
     res.end(); 
     return; 
    } 

    // Check if file/directory 
    if(stats.isFile()){ 
     const mimeType = mimeTypes[path.extname(fileName).split(".").reverse()[0]]; 
     res.writeHead(200, {'Content-type': mimeType}); 

     const fileStream = fs.createReadStream(fileName); 
     fileStream.pipe(res); 
    } else if(stats.isDirectory()){ 
     res.writeHead(302,{ 
      'Location' : 'index.html' 
     }); 
     res.end(); 
    } else { 
     res.writeHead(500, {'Content-type' : 'text/plain'}); 
     res.write('500 Internal Error\n'); 
     res.end(); 
    } 
}).listen(3000); 

私は単にテストし、代わりに、ブラウザで私が見つかりません404ページを取得することをレンダリングするの言うindex.htmlページがあります。私はserver.jsファイルを微調整して以来、問題はそこにあると信じていますが、私はあまりよく分かりません。

私はこのプロジェクトで持っているindex.htmlファイルをより良いサーバに書き込むために、このサーバコードがどのように書き込まれているのでしょうか。おそらく、

+0

インデックスファイルが間違った場所にあると仮定します。 consolde.log( 'Loading' + uri)という行は何を出力しますか?また、404を書き出すcatch(e)では、console.log(e)とconsole.log(e.stack)を試してみてください。これにより、問題を解決するための詳細情報が得られます。 –

答えて

0

stats = fs.lstatSync(fileName); 

ない:

stats = fs.lstatSync(filename); 

あなたは間違っている変数/ PARAMを持っている...それは大文字と小文字を区別します。

+0

トーマス、私の悪い、私は私のコードのすべてのファイル名を修正したと思った。 – Daniel

+0

私のコードにはまだまだ問題がありますが、私はconst statsでそれを考えています。それはvar statsであるべきですか? – Daniel

+0

私はこの時点で推測していますが、res.end()を追加することもできます。 after fileStream.pipe(res) – Thomas

関連する問題