1

I finally got everything working on a certain page, but the issue I'm facing now is when I create additional pages. I realize the issue must be with my routing, but I'm not sure how to change the server side code without effecting my app.

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

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

io.on('connection', function(socket){
  // socket functions
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});

I would like to serve html in a folder 'public' and have files like index.html and other.html in there.

DRB
  • 633
  • 11
  • 24
  • So, basically you're asking how to serve static files with Node ? – adeneo May 21 '15 at 11:11
  • possible duplicate of [Express-js can't GET my static files, why?](http://stackoverflow.com/questions/5924072/express-js-cant-get-my-static-files-why) – Ben Fortune May 21 '15 at 11:29

2 Answers2

1

Configure your express app to use a static directory.

app.use(express.static('public'));

All files located under public can now be accessed. So a file called index.html can now be reached via /index.html

Further documentation can be found here:

http://expressjs.com/starter/static-files.html

Exinferis
  • 689
  • 7
  • 17
  • Ah, great - this is exactly what I was looking for, thank you for the link as well. I will read more into this. I changed my code to: var app = require('express')(), http = require('http').Server(app), io = require('socket.io')(http), express = require('express'); app.use(express.static('public')); – DRB May 21 '15 at 11:20
-2

If your folder is called public then you could do something like

app.use(express.static('./public'))
    .get('/', function(req, res) {
        res.sendFile('index.html', {root: 'public/'});
    })
Dan Moldovan
  • 3,576
  • 2
  • 13
  • 24