我无法加载目录中存在的HTML文件。我只能加载默认的快递页面。下面给出的代码适用于2个文件index.js和index.html。这两个文件都位于同一目录中。
index.js
const express = require('express');
const http = require('http');
const morgan = require('morgan');
const hostname = 'localhost';
const port = 3000;
const app = express();
app.use(morgan('dev'));
app.use(express.static(__dirname + '/public'));
app.use((req, res, next) => {
console.log(req.headers);
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
res.end('<html><body><h1>This is an Express Server</h1></body></html>');
});
const server = http.createServer(app);
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
index.html
<html>
<title>This is index.html</title>
<body>
<h1>Index.html</h1>
<p>This is the contents of this file</p>
</body>
</html>
This is the output I am getting. I want to load my index.html not this default page.
答案 0 :(得分:0)
将 index.html 保留在 public 文件夹中,而不放在根目录中。 像这样:
House