要使用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下载此示例:
- https://github.com/rsp/node-express-static-example
有和没有Express的情况下,更多示例可以执行相同操作:
- https://github.com/rsp/node-static-http-servers



