LoginSignup
masafuru7396
@masafuru7396 (sh1)

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

CSSで画像を読み込みたい

CSSのbackground-imageを使って画像を表示したいのですが、画像ファイルを読み込んでくれません。

↓ 現在のファイル構成

image.png

index.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <h1>Hello world</h1>
    <div id="icon"></div>
</body>
</html>
style.css
body {
    background: #00bfff;
}

#icon {
    width: 100px;
    height: 100px;
    background-image: url(./icon/file_icon.png);
    background-size: cover;
}
server.js
const http = require('http');
const fs = require('fs');
const path = require('path')

var server = http.createServer(
    (request,response)=>{

        const requestPath = request.url

        if(requestPath === '/')
            fs.readFile('./index.html','UTF-8',(error,data)=>{
                response.writeHead(200, {'Content-Type':'text/html'});
                response.write(data);
                response.end();
            })
        else if(requestPath === '/style.css')
            fs.readFile('./style.css','UTF-8',(error,data)=>{
                response.writeHead(200, {'Content-Type':'text/css'});
                response.write(data);
                response.end();
            })
        else if(requestPath === './icon/file_icon.png')
        fs.readFile('./icon/file_icon.png','UTF-8',(error,data)=>{
            response.writeHead(200, {'Content-Type':'image/png'});
            response.write(data);
            response.end();
        })
    }
);

server.listen(3000);
console.log("Server running at http://localhost:3000")

↓ webサーバー経由で出した画像(画像が出ない)
image.png

↓ htmlファイルを直接開いた画像(画像が出る)
image.png

webサーバー経由でどうしたら画像ファイルを読み込めますか?
また、iconファイルに複数の異なる画像ファイル(jpgやsvrなど)がある場合はどうでしょうか?

0

5Answer

else if(requestPath === './icon/file_icon.png')

else if(requestPath === '/icon/file_icon.png')

に直してください。

1Like

Comments

  1. @masafuru7396

    Questioner

    ありがとうございます。残念ながらうまくいきませんでした(><)

  2. では const requestPath = request.url の次の行に console.log(requestPath) を書いてみてください。これでページをリロードすると、サーバを起動しているターミナルに requestPath が表示されます。画像を指すパスが表示されたら、それを使って if 文を書き直してください。

HTMLとCSSはローカルではなくて結局HTTPでデータもらうので、「.」つける必要がないです。

server.js

else if(requestPath === '/icon/file_icon.png')

style.css

#icon {
    width: 100px;
    height: 100px;
    background-image: url(/icon/file_icon.png);
    background-size: cover;
}
1Like

質問者さんの目的が、node.js 開発サーバーの使い方の勉強ではなくて、Visual Studio Code を使っての html, css の勉強であれば、拡張機能の Live Server を使ってはいかがですか?

VSCodeでWeb開発が楽になる!拡張機能Live Serverの使い方まとめ!
https://kosiro.tech/dev/how-to-use-liveserver.html

ググれば他にも参考になりそうな記事がいろいろヒットしますので、調べてみてください。


【追記】

Live Server 拡張機能をインストールして [Go Live] をクリックすると、

LiveServer.jpg

Live Server が立ち上がって自動的にブラウザが立ち上がって以下のように表示され、その後は localhost のポート 5500 でリッスンしてくれるようになります。

result.jpg

1Like

Comments

  1. @masafuru7396

    Questioner

    ダメです。サーバー再起動、VSCode再起動もダメでした。

  2. ああ、Node.jsの話でしたか。タグを見落としてました。
    この場合 requestPath には /icon/file_icon.png が入りますね。
    @uasi さんの回答はそういうことです。

    つまりURIのパスは正規化されているわけなんですが、その正規化はサーバーがやっているのかクライアント(ブラウザー)がやってるのか、どっちなのかなと思ってパケットキャプチャして見てみたら、どうやらクライアントがGETリクエストする段階で既に正規化してるようですね。

  3. @masafuru7396

    Questioner

    ありがとうございます。ご回答の内容だとうまくいきませんでした(><)

  4. あとは、サーバーにアップロードしたファイル名やディレクトリ名の大文字と小文字が合っているかを確認してみてください。もしローカル環境がWindowsだと、それが違っていても開けちゃうので。

みなさんアドバイスありがとうございます!
Node.jsを使うのは業務上の指示でして、結局は以下のように解決しました。
参考サイト:https://www.kipure.com/article/225/
「NodeJS 画像をHTMLで表示する」

server.js内に、受け取ったrequestのContent-Typeごとにタイプを書き換えるような関数を作成します。

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

var server = http.createServer(function (req, res) { 

  var url = '.'+(req.url.endsWith("/") ? req.url + "index.html" : req.url);
  //URLの最後が/ならindex.htmlを表示し、それ以外はそのURLのファイル名を変数へ。

    if (fs.existsSync(url)) {
    //ファイルがあれば
    fs.readFile(url, (err, data) => {
      if (!err) {
        
        res.writeHead(200, {"Content-Type": getType(url)});  //タイプを関数で切り替える
        res.end(data);
      }
    });
  }
}).listen(3000);
console.log("Server starting at port:3000");

function getType(_url) {
  //拡張子をみて一致したらタイプを返す関数
  var types = {
    ".html": "text/html",
    ".css": "text/css",
    ".js": "text/javascript",
    ".png": "image/png",
    ".jpg": "image/jpeg",
    ".gif": "image/gif",
    ".svg": "svg+xml"
  }
  for (var key in types) {
    if (_url.endsWith(key)) {
      return types[key];
    }
  }
  return "text/plain";
}

htmlファイルの中にimgタグで画像を貼る

index.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <h1>Hello world</h1>
    <div id="icon">
        <img src="icon/file_icon.png">
    </div>
</body>
</html>

以上でなんとか画像を表示させることができました。

image.png

ありがとうございました!

0Like

Comments

  1. 最初の質問の、

    <div id="icon"></div>
    
    #icon {
        width: 100px;
        height: 100px;
        background-image: url(./icon/file_icon.png);
        background-size: cover;
    }
    

    と、上の回答の、

    <div id="icon">
        <img src="icon/file_icon.png">
    </div>
    

    ではまるで話が違いますよ。分かってやってますか? 

    何でもいいから画像が表示されればいいということだったのですか? ブラウザで画像が表示される仕組みを理解されているでしょうか?

Your answer might help someone💌