Issue
I have developed a simple server in Node.js using Express and I have set the public
folder to serve static files.
In my root index.js
, I have the following code:
const express = require('express');
const app = express();
const http = require('http').Server(app);
const fs = require('fs');
app.use(express.static(__dirname + '/public'));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/public/index.html');
});
http.listen(3000, () => console.log('started server on *:3000'));
And the directory structure is:
root
|---index.js
|---package.json
|---public
| |---index.html
| |---cs
| | |---index.css
| |---js
| | |---index.js
In the index.html
in the public
folder, I have the following code:
<head>
<script src="js/index.js"></script>
<link rel="stylesheet" src="css/index.css" type="text/css" >
</head>
But no CSS is being rendered. How can I resolve this?
Solution
Replace src
attribute in link
tag to href
. If this doesn’t work then try below solution.
I’m considering your server is running on http://localhost:3000/
So update the url in src
of your index.html
in public folder by appending with the base url as I did below.
<head>
<script src="http://localhost:3000/js/index.js"></script>
<link rel="stylesheet" href="http://localhost:3000/css/index.css" type="text/css" >
</head>
Answered By – Abhishek Pankar
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0