LoginSignup
16
14

More than 5 years have passed since last update.

Node.jsで書いたWebサーバでJSやCSSを読み込む

Last updated at Posted at 2017-12-04

Node.jsでWebサーバを書く必要があってHTMLからJSやCSSのファイルが読み込めなかったのでその解決策
まずはindex.htmlを返すサーバを書いてみる

server.js
var http = require('http');
var fs = require('fs');

http.createServer(function(req,res){
  fs.readFile('./index.html',function(err,data){
    res.writeHead(200,{"Content-Type":"text/html"});
    res.end(data,'utf-8');
  });
}).listen(8888); 

index.htmlでは./js/index.jsを読み込んでいる

index.html
<html>
  <head>
    <script type="text/javascript" src="./js/index.js"></script>
  </head>
  <body onload="hello()">
    <h1>Hello!</h1>
  </body>
</html>

index.jsの中身は今回単純にアラートを出すだけにしておく

js/index.js
function hello(){
  alert("Hello!!");
}

この状態でサーバを起動させるとjs/index.jsは読み込まれずに

その内容はindex.htmlとして扱われる

スクリーンショット 2017-12-04 20.27.25.png

修正

server.jsを編集してjs/index.jsを読み込むようにする

server.js
var http = require('http');
var fs = require('fs');

http.createServer(function(req,res){
  var url = req.url; //リクエストからURLを取得
  var tmp = url.split('.'); //splitで . で区切られた配列にする 
  var ext = tmp[tmp.length - 1]; //tmp配列の最後の要素(外部ファイルの拡張子)を取得
  var path = '.' + url; //リクエストされたURLをサーバの相対パスへ変換する
  switch(ext){
    case 'js': //拡張子がjsならContent-Typeをtext/javascriptにする
       fs.readFile(path,function(err,data){
         res.writeHead(200,{"Content-Type":"text/javascript"});
         res.end(data,'utf-8');
       });
       break;
     case '/': //拡張子が/(index.html)だった場合はindex.htmlを返す
       fs.readFile('./index.html',function(err,data){
         res.writeHead(200,{"Content-Type":"text/html"});
         res.end(data,'utf-8');
       })
       break;
  }
}).listen(8888);

とするとサーバ内においてあるjsファイルやcssファイルを読み込める
スクリーンショット 2017-12-04 21.02.56.png

ちょっと悩んだので覚書程度に

16
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
14