2016-08-06 39 views
0

特にサーバー側の開発とnode.jsに精通していませんが、複数の.css.jsファイルを使用するWebアプリケーションには必要です。シンプルなWebサーバーは、クライアント要求ごとにこれらのファイルを送信する必要があります。私は.html' file, but if I include .js files to .html`のためにそれをしました。それはページにロードされません。複数のファイルを単一のレスポンスでクライアントに返す方法

これは、正しく設定する必要があるレスポンスヘッダーのためだと思いますか?または、私はクライアントに応答したい各ファイルをサーバー側で読み込む必要がありますか?

サーバコード:

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

var port = 8080; 
var files = ["app.html", "math.js"];   
http.createServer(function(request, response) { 

    fs.readFile('app.html', 'utf8', function(err, data) { 
     if (err) { 
      return console.log(err); 
     } 

     response.setHeader('Content-type', 'text/html'); 
     response.end(data); 
    }); 


}).listen(port); 

console.log("listening on port: " + port); 

app.htmlファイル

<!doctype html> 
<html> 
    <head> 
     <title>| Demo1</title> 
     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 


    </head> 
    <body> 
     <h1>Loaded</h1> 
     <h2>Loaded</h2> 
     <h3>Loaded</h3> 

     <canvas width="700" height="700" id="cnv"></canvas> 
     <script type="text/javascript" src="math.js"></script> 
    </body> 
</html> 

P.S.エクスプレスやフード内のすべての作業を行うモジュールのようなフレームワークは提案しないでください。私は、この目的のためにnode.js APIを使用する方法を理解する必要があります。

答えて

0

は、この解決策を見つけ、私はそれはいくつかの単純な静的なWebサーバー

var http = require('http'); 
var url = require('url'); 
var path = require('path'); 
var fs = require('fs'); 
var port = 8080; 

var appMainFileName = "app.html"; 
var mimeTypes = { 
    "html": "text/html", 
    "jpeg": "image/jpeg", 
    "jpg": "image/jpeg", 
    "png": "image/png", 
    "js": "application/javascript", 
    "css": "text/css" 
}; 

http.createServer(function(request, response) { 

    var uri = url.parse(request.url).pathname, 
    fileName = path.join(process.cwd(), uri);  

    fs.exists(fileName, function(exists) { 
    if (!exists) { 
     response.writeHead(404, {"Content-Type": "text/plain"}); 
     response.write("404 Not Found\n"); 
     response.end(); 
     return; 
    } 

    if (fs.statSync(fileName).isDirectory()) { 
      fileName += '/' + appMainFileName; 
     } 

    fs.readFile(fileName, "binary", function(err, data) { 
     if (err) {   
     response.writeHead(500, {"Content-Type": "text/plain"}); 
     response.write(err + "\n"); 
     response.end(); 
     return; 
     } 

     response.writeHead(200, {"Content-Type": mimeTypes[ fileName.split(".")[1] ]}); 
     response.write(data, "binary"); 
     response.end(); 
    }); 
    }); 


}).listen(port); 
を書くために必要な知っていました
関連する問題