2016-09-24 7 views
0

経由でHTMLに利用可能な他のファイルは、私はこのような非常に単純なWebサーバーを持っている:作りJSとのNode.js HTTPサーバー

var http = require('http'); 
var fs = require('fs'); 

http.createServer(function (req, res) { 

    res.writeHead(200, { 'Content-Type': 'text/html' }); 
    fs.readFile('./index.html', 'utf-8', function (err, content) { 
    if (err) { 
     res.end('something went wrong.'); 
     return; 
    } 
    res.end(content); 
    }); 

}).listen(8080); 
console.log("Server running on port 8080.") 

これは何の問題もなく私のindex.htmlをレンダリングしますが、私は、参照しようとした場合私のindex.html内の別のファイル、例えばスクリプトタグを介して、サイトはちょうど立ち往生し、サーバディレクトリに存在するファイルを見つけることができません。

これらのファイルをindex.htmlファイルで使用できるようにするにはどうすればよいですか?

これは、Expressではるかに簡単に行うことができることを認識していますが、Expressは使用しません。私は物事がその場でどのように働くのかを学びたいと思っています。前もって感謝します。

答えて

0

ディレクトリをpublicにする必要があります。 Node.jsアプリケーションの開発中にフレームワークを使用することをお勧めします。

以下は、フレームワークのないサーバーファイルのコードです。

var basePath = __dirname; 
var http = require('http'); 
var fs = require('fs'); 
var path = require('path'); 

http.createServer(function(req, res) { 
    var stream = fs.createReadStream(path.join(basePath, req.url)); 
    stream.on('error', function() { 
     res.writeHead(404); 
     res.end(); 
    }); 
    stream.pipe(res); 
}).listen(9999); 

参照してください:Node itself can serve static files without express or any other module..?

+0

を参照していただき、ありがとうございます。それは私がこの脆弱性を理解するのに役立ちます – jgozal

関連する問題