Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express.js index.js 404 (Not Found)

For some reason it can't load my index.js script that is being referenced from my index.html. server.js, index.html, and index.js are all located at the root of my project folder.

server.js

var express = require('express'),
    app = express();

app.set("view options", {layout: false});
app.use(express.static(__dirname + '/public'));
app.set('views', __dirname + '/');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

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

app.listen(4000, function () {
    console.log('Example app listening on port 4000!');
});

index.html

<html>
    </head></head>
    <body>
        <div class="ink-grid vertical-space">
            <div id="content">
                <div class="panel vertical-space">
                    <div id="app"/>
                </div>
            </div>
        </div>
        <script type="text/babel" src="index.js"></script>
    </body>
</html>
like image 537
PositiveGuy Avatar asked Feb 16 '26 22:02

PositiveGuy


2 Answers

You have to serve those files. You could do them individually:

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

Or create a directory (e.g. www) for everything you want to serve and use express.static:

app.use(express.static('www'));
like image 125
Kable Avatar answered Feb 18 '26 16:02

Kable


By looking declaration

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

Your index.js file should be in the public directory.

Since index.js and server.js are in the same directory, define

app.use(express.static(.));
like image 28
RIYAJ KHAN Avatar answered Feb 18 '26 17:02

RIYAJ KHAN