Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
329 views
in Technique[技术] by (71.8m points)

html - 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";
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...