0

I want to load index.html when I request http://localhost:4935/ so my code for this is like

const MODULES_DIR = '/usr/local/lib/node_modules/';
const APP_PORT = 4935;

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

server.listen(APP_PORT);

app.get('*', function (req, res) {
    if (fs.existsSync(__dirname + req.route.params))
        res.sendfile(__dirname + req.route.params);

    if (req.route.params == '/')
        res.sendfile(__dirname + '/index.html');
});

On this i get error:

web@web-X501A1 ~ $ node '/home/web/www/nodechat/server.js' 
   info  - socket.io started

http.js:691
    throw new Error('Can\'t set headers after they are sent.');
          ^
Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (http.js:691:11)
    at ServerResponse.res.setHeader (/usr/local/lib/node_modules/express/node_modules/connect/lib/patch.js:63:22)
    at SendStream.type (/usr/local/lib/node_modules/express/node_modules/send/lib/send.js:456:7)
    at SendStream.send (/usr/local/lib/node_modules/express/node_modules/send/lib/send.js:348:8)
    at /usr/local/lib/node_modules/express/node_modules/send/lib/send.js:323:10
    at Object.oncomplete (fs.js:107:15)

As i understand from error the problem is that res.sendfile can be sent only once... Basically i need to automatically load all JS and CSS.

0

1 Answer 1

1

Instead of this:

app.get('*', function (req, res) {
  ...
});

Use this:

app.use(express.static(__dirname));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.