使用 Node 加载 html 页面

Load in html page with Node

我是 node.js 的新手 - 请原谅我的无能。

我已经按照 w3school 的教程在我的计算机 localhost:8080 上设置了一个基本节点应用程序。

var http = require('http');

http.createServer(function (req, res) {
   res.writeHead(200, {'Content-Type': 'text/html'});
   res.end('Hello World!');
}).listen(8080);

这工作正常,在我的本地主机上显示 hello world。但是,我似乎无法找到一种方法来加载同一文件夹级别的单独 html 文档。我正在尝试这样做:

var http = require('http');
const express = require('express');
const app = express();

http.createServer(function (req, res) {
    res.render('index');
}).listen(8080);

我已经将 express 下载到 master 文件夹中,但我的终端中仍然出现错误 "TypeError: res.render is not a function"。我该如何解决这个问题?

作为替代方案,您还可以使用 Express static middleware and create a route method 通过提供文件来响应对页面根目录的 GET 请求。此外,为避免文件路径的平台特定问题,您可以使用 path.join(),其中 __dirname 设置工作目录的绝对路径。

const http = require('http');
const path = require('path');
const express = require('express');
const app = express();    

app.use(express.static(path.join(__dirname, '')));

app.get('/', function (req, res) {
    res.sendFile(path.join(__dirname, 'index.html'));
});

http.createServer(app).listen(8080, function(){
    console.log('HTTP server listening on port 8080');
});