index.html文件未加载到我的express服务器上

index.html文件未加载到我的express服务器上,express,Express,我无法加载目录中的HTML文件。我只能加载默认的express页面。下面给出的代码适用于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 ap

我无法加载目录中的HTML文件。我只能加载默认的express页面。下面给出的代码适用于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}/`);
});
const express=require('express');
const http=require('http');
const morgan=要求(“摩根”);
常量主机名='localhost';
常数端口=3000;
常量app=express();
应用程序使用(摩根(“开发”);
app.use(express.static(uu dirname+/public));
应用程序使用((请求、恢复、下一步)=>{
控制台日志(请求头);
res.statusCode=200;
res.setHeader('Content-Type','text/html');
res.end('这是一台Express服务器');
});
const server=http.createServer(app);
侦听(端口、主机名,()=>{
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>

这是index.html
Index.html
这是该文件的内容


将您的index.html保存在public文件夹中,而不是根目录中。 像这样:

public
     index.html
index.js