Node.js does not load js or css scripts

Asked

Viewed 1,566 times

2

I’m making a chat app and I can get the page I want but this page does not load the corresponding css or js scripts, does anyone have a solution for this please? So far I’ve got this:

Code:

server.js:

var socket  = require( './node_modules/socket.io' );
var express = require('./node_modules/express');
var app     = express();
var server  = require('http').createServer(app);
var io      = socket.listen( server );
var port    = process.env.PORT || 3000;
var users = [];

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

io.on('connection', function(socket){
  socket.on('chat message', function(msg){
    io.emit('chat message', 'isto veio do server: ' +msg);
  });
});

server.listen(port, function () {
  console.log('Server listening on port %d', port);
});

index.html:

...
<link rel="stylesheet" type="text/css" href="/styles/estilos.css"> <!-- este não carrega -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.6/socket.io.js"></script>
<script src="scripts/funcs.js"></script> <!-- este não carrega -->
...

1 answer

2


You have to set up in your server.js a base directory so that html can make use of resources. Put this next to var users = [] and see if it works:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.