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ファイルを読み込んでくれません

解決したいこと

node.jsでwebサーバーを構築し、vscodeで作成したhtmlファイルをブラウザで表示したのですが、cssファイルの内容が反映されません。htmlに直接style属性を記述すると表示に反映されるのですが。。
どうすればcssファイルの内容が反映されますか。

該当するソースコード

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>
</body>
</html>
style.css
body {
    background: #00bfff;
}
server.js
const http = require('http');
const fs = require('fs');

var server = http.createServer(
    (request,response)=>{
        fs.readFile('./index.html','UTF-8',(error,data)=>{
            response.writeHead(200, {'Content-Type':'text/html'});
            response.write(data);
            response.end();
        })
       
    }
);
server.listen(3000);
console.log("Server running at http://localhost:3000")

この内容だと、真っ白な画面に「Hello world」と出るだけです。

index.htmlを

index.html
<!DOCTYPE html>
<html lang="js">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body style="background: #00bfff;">
    <h1>Hello world</h1>
</body>
</html>

こうすると、背景が青くなり設定が反映されます。
どうすればcssファイルを読み込んでくれるのか、教えてください。

0

1Answer

「http」サーバーが「style.css」を提供してないからです。

server.jsを下のように修正してみてください。

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

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

        const requsetPath = request.url

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

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

Comments

  1. @masafuru7396

    Questioner

    ありがとうございます!無事、反映させることができました!

Your answer might help someone💌