Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/85.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用节点加载html页面_Html_Node.js_Express_Node Modules - Fatal编程技术网

使用节点加载html页面

使用节点加载html页面,html,node.js,express,node-modules,Html,Node.js,Express,Node Modules,我是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); 这可以正常工作

我是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下载到主文件夹中,但我仍然在终端中收到错误,“TypeError:res.render不是函数”。如何修复此问题?

作为一种替代方法,您还可以使用Express并创建一个用于通过提供文件来响应对页面根目录的GET请求的。此外,为了避免平台特定的文件路径问题,您可以使用
path.join()
,其中
\uu 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');
});