我正在用NodeJS编写应用程序。
我在同一目录中有两个文件,但是每当我调用其中一个时:
window.location.href = "./page.html";
window.location.href = "/page.html";
从我的index.html加载资源失败错误。
谢谢!
要使用Express提供静态文件,您应该使用express.static
或以其他方式为每个拥有的html文件定义一个新路径,或者重新发明所提供的功能express.static
。
您可以执行以下操作:
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的情况下,更多示例可以执行相同操作: