Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8906

Node.jsでhtmlのlinkタグなどから外部ファイルを読み込めないときの解決法

$
0
0

Node.jsでJavaScript入門書のサンプルコードを実行したが、htmlのlinkタグとscriptタグでcssとJavaScriptが読み込まれなかった。

なお学習目的のため以下の条件を設けている

  • Expressなどのフレームワークは使わない
  • サンプルのディレクトリ構造は変えない

サンプルコード

入門書のコードをそのままここに書くわけにはいかないので、自作のサンプルコードを記しておく。

ディレクトリ構成図

.
├── common
│   ├── jquery-3.4.1.min.js
│   └── style.css
└── samples
    ├── sample1
    │   ├── index.html
    │   └── script.js
    └── sample2

  
ピンク色の「うんこ」を表示するサンプルコード

index.html
<!DOCTYPE html><htmllang="ja"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><metahttp-equiv="X-UA-Compatible"content="ie=edge"><title>sample1</title><linkhref="../../common/style.css"rel="stylesheet"></head><body><h1>うんこ</h1><script src="../../common/jquery-3.4.1.min.js"></script><script src="./script.js"></script></body></html>
style.css
h1{font-size:60px;color:deeppink;}

cssを読み込めれば同じ方法でJavaScriptも読み込めるはずなのでJavaScriptは割愛。

Node.jsで実行してみる

上記のサンプルコードをNode.jsで実行するためsample1/app.jsを作成

app.js
consthttp=require('http');constfs=require('fs');constindexHtml=fs.readFileSync('./index.html')constserver=http.createServer((req,res)=>{res.writeHead(200,{'Content-Type':'text/html'});res.write(indexHtml);res.end();});constport=8000;server.listen(port,()=>{console.info(`Listening on ${port}`);});

$ node app.jsで実行しhttp://localhost:8000にアクセスすると

キddャプチャ.PNG

黒い。cssを読み込んでない。

考察

console.log(req.url)を追記

app.js
constserver=http.createServer((req,res)=>{console.log(req.url)res.writeHead(200,{'Content-Type':'text/html'});res.write(indexHtml);res.end();});

  
再度$ node app.jsで実行しhttp://localhost:8000にアクセス後コンソールを見てみると

/
/common/style.css
/common/jquery-3.4.1.min.js
/script.js
/favicon.ico

http://localhost:8000/common/style.cssなどにリクエストしてしている

http://localhost:8000/common/style.cssにアクセスしてみると
キssssssャプチャ.PNG

http://localhost:8000へのリクエストに対しindex.htmlをレスポンスとして返したのと同様に

http://localhost:8000/common/style.cssへのリクエストに対してレスポンスとしてsyle.cssを返すようにルーティングしてあげればよさそう。

解決方法

app.js
consthttp=require('http');constfs=require('fs');constindexHtml=fs.readFileSync('./index.html')conststyleCss=fs.readFileSync('../../common/style.css')constserver=http.createServer((req,res)=>{switch(req.url){case'/':res.writeHead(200,{'Content-Type':'text/html'});res.write(indexHtml);res.end();break;case'/common/style.css':res.writeHead(200,{'Content-Type':'text/css'});res.write(styleCss);res.end();break;default:break;}});constport=8000;server.listen(port,()=>{console.info(`Listening on ${port}`);});

  
$ node app.jsで実行しhttp://localhost:8000にアクセスすると

ddddキャプチャ.PNG

成功。同じ要領でJavaScriptも読み込める。


Viewing all articles
Browse latest Browse all 8906

Trending Articles