Kristoffer Abell Kristoffer Abell - 4 months ago 14
Node.js Question

Failed to load resource from same directory when redirecting Javascript

I am writing an application in NodeJS.

I have two files in the same directory but whenever I call either:



window.location.href = "./page.html";


window.location.href = "/page.html";





from my index.html I get a failed to load resource error.

Thanks!

rsp rsp
Answer

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.

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+'/');
});

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 = "./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 = "./index.html";
}, 2000);
</script>
</body>
</html>

And the files will redirect every 2 seconds.

You can download this example from GitHub: