2017-02-23 16 views
0

非常に基本的なnode.jsサーバーを使用していくつかの静的ファイルを提供しようとしています。目的は、javascriptファイルを参照するスクリプトタグを使用してhtmlファイルを提供することです。 ブラウザでアプリケーションを開くときに、htmlレンダリングがうまくいけば、問題はjsファイルにあります。ブラウザでは、jsファイルにはjsコードではなくhtmlコードがあります。Node.jsを使用してJavascriptファイルを提供する

ServerCにはCODE:

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

var port = 3000; 

var app = http.createServer(function(req, res){ 
    var html = fs.createReadStream('./index.html') 

    html.pipe(res); 
}) 

app.listen(port, function(){ 
    console.log('Listening on port ' + port) 
}) 

HTML CODE(index.htmlを):

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="utf-8"> 
    <title>Hello</title> 
</head> 
<body> 
    <h1>Hello</h1> 
    <script src="./some.js"></script> 
</body> 
</html> 

JAVASCRIPT CODE(some.js):

console.log("Hello") 

ディレクトリ構造:

|-index.html 
|-some.js 
|-app.js(server) 

答えて

3

私はその後、あなたが作成し、そのディレクトリにサービスを提供するexpress.static使用し、次のように

|-public 
    |-index.html 
    |-some.js 
|-app.js(server) 

をご提供するために必要なファイル用のディレクトリを作成するようアドバイスしています。

var express = require('express'); 
var app = express(); 
var path = require('path'); 
var port = 3000; 

app.use(express.static(path.join(__dirname, 'public'))); 

app.listen(port, function(){ 
    console.log('Listening on port ' + port) 
}) 

次に、あなたはちょうどあなたが応答のために、以下の

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

http.createServer(function (request, response) { 

    var filePath = '.' + request.url; 
    if (filePath == './') 
     filePath = './index.html'; 

    var extName = path.extname(filePath); 
    var contentType = 'text/html'; 
    switch (extName) { 
     case '.js': 
      contentType = 'text/javascript'; 
      break; 
     case '.css': 
      contentType = 'text/css'; 
      break; 
    } 

    path.exists(filePath, function(exists) { 

    if (exists) { 
     fs.readFile(filePath, function(error, content) { 
      if (error) { 
       response.writeHead(500); 
       response.end(); 
      } 
      else { 
       response.writeHead(200, { 'Content-Type': contentType }); 
       response.end(content, 'utf-8'); 
      } 
     }); 
    } 
    else { 
     response.writeHead(404); 
     response.end(); 
    } 
    }); 
}); 
+0

感謝を行うことができますが、私の目的は、フレームワークなしでそれを行うことです表明使用しない

node app.js 

を実行します。 – 2K01B5

+1

私の応答に新しい例を追加しました:) –

関連する問題