Failed to load resource from same directory when redirecting Javascript

To serve static files with Express, you should use express.static or otherwise you will have to define a new route for every html file that you have, or reinvent the functionality provided by express.static. (If you don’t want to use Express for that then see this answer.)

You can do something like this:

app.js

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

var htmlPath = path.join(__dirname, 'html');

app.use(express.static(htmlPath));

var server = app.listen(3000, function () {
    var host="localhost";
    var port = server.address().port;
    console.log('listening on http://'+host+':'+port+"https://stackoverflow.com/");
});

Put your files in the html subdirectory. For example:

html/index.html

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>index.html</title>
</head>
<body>
<h1>index.html</h1>
<p>Redirection in 2s...</p>
<script>
setTimeout(function () {
   window.location.href = "https://stackoverflow.com/questions/38441863/./page.html";
}, 2000);
</script>
</body>
</html>

html/page.html

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>page.html</title>
</head>
<body>
<h1>page.html</h1>
<p>Redirection in 2s...</p>
<script>
setTimeout(function () {
   window.location.href = "https://stackoverflow.com/questions/38441863/./index.html";
}, 2000);
</script>
</body>
</html>

And the files will redirect every 2 seconds.

You can download this example from GitHub:

More examples to do the same with and without Express:

Other related answers:

Leave a Comment