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

在Node.js中返回HTML内容给客户端,通常有两种方式:直接返回静态HTML字符串,或通过模板引擎动态渲染页面。无论哪种方式,核心都是设置正确的响应头并发送HTML内容。
适合简单场景,比如返回一个内联的HTML页面或维护提示页。
text/html
示例代码:
const http = require('http');
const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
  const html = `
    <!DOCTYPE html>
    <html>
      <head><title>Node.js 页面</title></head>
      <body>
        <h1>欢迎访问 Node.js 服务</h1>
        <p>这是通过 res.end() 直接返回的 HTML 内容。</p>
      </body>
    </html>
  `;
  res.end(html);
});
server.listen(3000, () => {
  console.log('服务器运行在 http://localhost:3000');
});
当需要动态数据插入HTML时,推荐使用模板引擎。以 EJS 为例:
立即学习“前端免费学习笔记(深入)”;
npm install ejs
示例目录结构:
/views index.ejs app.js
views/index.ejs 文件内容:
<!DOCTYPE html>
<html>
  <head><title><%= title %></title></head>
  <body>
    <h1><%= message %></h1>
  </body>
</html>
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 是最常用的 Node.js Web 框架,内置对模板引擎的支持。
npm install express ejs
示例:
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配合模板引擎,便于维护和扩展。
以上就是nodejs如何添加html_Node.js服务端HTML渲染与响应方法的详细内容,更多请关注php中文网其它相关文章!
                        
                        HTML怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
                
                                
                                
                                
                                
                                
                                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号