1

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!

Kristoffer Abell
  • 323
  • 4
  • 17
  • What does it have to do with Node? Can you access both files when you type in the URLs manually? – rsp Jul 18 '16 at 16:52
  • When I run it through Node I call: app.get('/', function(req, res){ res.sendFile(__dirname + '/index.html'); }); So when I visit the site I go to http://localhost:8000/. I don't really know any other way. – Kristoffer Abell Jul 18 '16 at 17:00
  • Use express static middleware to serve static files `app.use(express.static('public'));`, any file in public folder`/public/` will be served. See this https://expressjs.com/en/starter/static-files.html – Molda Jul 18 '16 at 17:11
  • Thank you so much! – Kristoffer Abell Jul 18 '16 at 17:32

1 Answers1

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:

More examples to do the same with and without Express:

Other related answers:

Community
  • 1
  • 1
rsp
  • 107,747
  • 29
  • 201
  • 177