Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node JS keep getting Failed to load resource error message

Tags:

node.js

I am currently testing out a node.js application and have tried to add:

<link rel="stylesheet" href="assets/css/formalize.css" />
<script src="assets/js/jquery.formalize.js"></script> 

to my code but keeping getting the error message:

Failed to load resource: the server responded with a status of 404 (Not Found) 

http://localhost:3000/assets/css/formalize.css

Failed to load resource: the server responded with a status of 404 (Not Found) 

http://localhost:3000/assets/js/jquery.formalize.js

Any idea where I'm going wrong? Here is my code so far (in app.js)

var express = require('express'),
    app = express(),
    server = require('http').createServer(app),
    io = require('socket.io').listen(server);

server.listen(3000);

app.get('/', function(req, res) {
    res.sendfile(__dirname + '/index.htm');
});

io.sockets.on('connection', function(socket) {
    socket.on('send message', function(data) {
        io.sockets.emit('new message', data);
    });
});
like image 242
methuselah Avatar asked Dec 07 '22 06:12

methuselah


1 Answers

You need to add the express.static middleware to your app and make it point to your directory with static assets.

For example, if you directory structure is set up like this:

app.js
index.htm
  static
    assets
      js
        jquery.formalize.js
      css
        formalize.css

You would specify your static asset directory like this:

app.use(express.static(__dirname + '/static'));

And reference your files in your html file like this:

<link rel="stylesheet" href="/assets/css/formalize.css"/>
<script src="/assets/js/jquery.formalize.js"></script> 
like image 122
go-oleg Avatar answered Feb 20 '23 13:02

go-oleg