Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js. Why is the page cannot load css and javascript file?

i have created a node.js server. When i entered the localhost using port 3000, it displayed text only without css or javascript. I have tried several solutions that have worked on others. but they didn't worked for me.

Node JS keep getting Failed to load resource error message

static files with express.js

Can not get CSS file

my file order is like this

server.js
index.html
 public
  css
   style.css

This is the code for the server

var express = require('express');
var app = express();
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');});
app.use(express.static(__dirname + 'public'));
app.listen(3000);

These are the errors

GET http://localhost:3000/ [HTTP/1.1 304 Not Modified 11ms]
GET http://localhost:3000/public/css/demo.css [HTTP/1.1 404 Not Found 10ms]
GET http://localhost:3000/public/css/themes/popclip.css [HTTP/1.1 404 Not Found 10ms]
GET http://localhost:3000/public/css/reveal.min.css [HTTP/1.1 404 Not Found 19ms]
GET http://localhost:3000/public/css/theme/default.css [HTTP/1.1 404 Not Found 12ms]
GET http://localhost:3000/public/css/jquery.dropdown.css [HTTP/1.1 404 Not Found 11ms]
GET http://localhost:3000/node_modules/socket.io/node_modules/socket.io-client/socket.io.js [HTTP/1.1 404 Not Found 10ms]
GET http://localhost:3000/public/js/jquery.min.js [HTTP/1.1 404 Not Found 29ms]
GET http://localhost:3000/public/js/jquery.popline.js [HTTP/1.1 404 Not Found 28ms]
GET http://localhost:3000/public/js/plugins/jquery.popline.link.js [HTTP/1.1 404 Not Found 28ms]
like image 870
Muhamad Syahir Mohd Hashim Avatar asked Jan 20 '15 03:01

Muhamad Syahir Mohd Hashim


2 Answers

This:

__dirname + 'public'

Should be:

__dirname + '/public'

Also it looks like your paths in your html/css may not be correct since __dirname + '/public' will be your root. So unless you have a directory __dirname + '/public/public' you will have to change the paths in your html/css.

like image 167
mscdex Avatar answered Nov 05 '22 01:11

mscdex


Problem solved.

The problem was in my index.html file. Originally I thought that when i created a new folder and put in all the css and js files there, I needed to add the 'public' in all the src. Like this

<script src="public/js/jquery.min.js"></script>
<script src="public/js/jquery.popline.js"></script>

But instead, I just have to do it without the 'public' folder like this

<script src="js/jquery.min.js"></script>
<script src="js/jquery.popline.js"></script>

and add '/' to the __dirname + 'public' to __dirname + '/public' like mscdex suggested.

like image 10
Muhamad Syahir Mohd Hashim Avatar answered Nov 05 '22 01:11

Muhamad Syahir Mohd Hashim