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!


Solution 1:

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

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:

  • https://github.com/rsp/node-express-static-example

More examples to do the same with and without Express:

  • https://github.com/rsp/node-static-http-servers

Other related answers:

  • How to serve an image using nodejs
  • onload js call not working with node
  • Sending whole folder content to client with express
  • Loading partials fails on the server JS
  • Node JS not serving the static image