在 Node.js 中输出 HTML 通常是通过创建一个简单的服务器来完成的。你可以使用内置的 http
模块或更高级的框架如 Express 来实现。以下是两种方法的示例:
使用 http 模块
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<h1>Hello, World!</h1><p>This is a simple HTML response from Node.js</p>');
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}`);
});
使用 Express 框架
首先,你需要安装 Express:
npm install express
然后,你可以这样创建一个简单的服务器:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('<h1>Hello, World!</h1><p>This is a simple HTML response from Express.</p>');
});
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}`);
});
运行代码
无论你选择哪种方法,都可以通过命令行运行你的 JavaScript 文件:
node yourFileName.js
将 yourFileName.js
替换为你保存代码的文件名。
之后,在浏览器中访问 http://localhost:3000
,你就会看到输出的 HTML 内容了。
内容由零声教学AI助手提供,问题来源于学员提问