Node.js中返回HTML可通过原生HTTP模块直接发送字符串或使用模板引擎动态渲染。直接返回时需设置Content-Type为text/html并用res.end()发送HTML内容;对于动态数据,可结合EJS等模板引擎读取模板文件并渲染数据后返回;更推荐在中大型项目中使用Express框架,配置视图引擎后通过res.render()便捷地响应HTML页面,提升可维护性与开发效率。

在Node.js中返回HTML内容给客户端,通常有两种方式:直接返回静态HTML字符串,或通过模板引擎动态渲染页面。无论哪种方式,核心都是设置正确的响应头并发送HTML内容。
直接返回HTML字符串
适合简单场景,比如返回一个内联的HTML页面或维护提示页。
- 使用 res.writeHead() 设置状态码和Content-Type为
text/html - 通过 res.end() 发送HTML内容
示例代码:
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
const html = `
Node.js 页面
欢迎访问 Node.js 服务
这是通过 res.end() 直接返回的 HTML 内容。
立即学习“前端免费学习笔记(深入)”;
`;
res.end(html);
});
server.listen(3000, () => {
console.log('服务器运行在 http://localhost:3000');
});
使用模板引擎渲染HTML(如EJS、Pug)
当需要动态数据插入HTML时,推荐使用模板引擎。以 EJS 为例:
- 安装 ejs:
npm install ejs - 创建模板文件(如 views/index.ejs)
- 在路由中读取模板并渲染数据
示例目录结构:
/views index.ejs app.js
views/index.ejs 文件内容:
<%= title %> <%= message %>
app.js 中使用 EJS 渲染:
const http = require('http');
const fs = require('fs');
const path = require('path');
const ejs = require('ejs');
const server = http.createServer((req, res) => {
const filePath = path.join(__dirname, 'views', 'index.ejs');
fs.readFile(filePath, 'utf8', (err, template) => {
if (err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
return res.end('模板读取失败');
}
const html = ejs.render(template, {
title: '动态页面',
message: 'Hello from EJS!'
});
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(html);
});
});
server.listen(3000);
使用 Express 框架简化HTML响应
Express 是最常用的 Node.js Web 框架,内置对模板引擎的支持。
- 安装 express 和 ejs:
npm install express ejs - 配置视图目录和引擎
- 使用 res.render() 发送渲染后的页面
示例:
const express = require('express');
const app = express();
// 设置模板引擎
app.set('view engine', 'ejs');
app.set('views', './views');
app.get('/', (req, res) => {
res.render('index', {
title: 'Express + EJS',
message: '这是通过 Express 渲染的页面'
});
});
app.listen(3000, () => {
console.log('服务启动在 http://localhost:3000');
});
基本上就这些。根据项目复杂度选择合适的方式:小项目可用原生返回HTML,中大型建议用Express配合模板引擎,便于维护和扩展。











