我正在用 NodeJS 编写一个应用程序。
我在同一目录中有两个文件,但每当我调用其中一个时:
window.location.href = "./page.html";
window.location.href = "/page.html";
从我的index.html 中,我收到加载资源失败错误。
谢谢!
最佳答案
要使用 Express 提供静态文件,您应该使用 express.static
,否则您必须为您拥有的每个 html 文件定义一个新路由,或者重新发明 express.static
提供的功能。 (如果您不想使用 Express,请参阅 this answer。)
你可以这样做:
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+'/');
});
将文件放入 html
子目录中。例如:
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>
文件每 2 秒就会重定向一次。
您可以从 GitHub 下载此示例:
使用和不使用 Express 执行相同操作的更多示例:
其他相关答案:
关于javascript - 重定向 Javascript 时无法从同一目录加载资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38441863/