Node.js 如何渲染HTML的纯文本

Node.js 如何渲染HTML的纯文本

Express Js是基于Node.js的Web应用程序框架,基于Node.js Web服务器功能帮助我们创建根据HTTP请求方法(POST,GET等)和请求的路由进行响应的应用程序端点。 express.js模块的res.sendFile()方法用于渲染本地机器上存在的特定HTML文件。

语法:

res.sendFile(path,[options],[fn])
JavaScript

参数: The path参数描述了路径,options参数包含了诸如maxAge、root等属性,fn是回调函数。

返回值: 它返回一个对象。

项目设置:

步骤1: 如果您的计算机上没有安装Node.js,请安装Node.js。

步骤2: 在public文件夹中创建一个名为public的新文件夹。在public文件夹中创建两个文件,分别为index.html和products.html

步骤3: 现在,在命令行上使用以下命令初始化一个带有默认配置的新Node.js项目。

npm init -y
JavaScript

步骤4: 现在在命令行中使用以下命令,在您的项目内安装express。

npm install express
JavaScript

项目结构: 按照以下步骤完成后,您的项目结构将如下所示。

Node.js 如何渲染HTML的纯文本

app.js

// Importing modules 
const express = require('express'); 
const path = require('path'); 
const app = express(); 
  
app.get('/', (req, res) => { 
  
  // Sending our index.html file as  
  // response. In path.join() method 
  // __dirname is the directory where 
  // our app.js file is present. In  
  // this case __dirname is the root 
  // folder of the project. 
  res.sendFile(path.join(__dirname, '/public/index.html')); 
}); 
  
app.get('/products', (req, res) => { 
  res.sendFile(path.join(__dirname, '/public/products.html')); 
}); 
  
app.listen(3000, () => { 
  console.log('Server is up on port 3000'); 
});
JavaScript

index.html

<!DOCTYPE html> 
<html lang="en"> 
  <head> 
    <meta charset="UTF-8" /> 
    <meta http-equiv="X-UA-Compatible" content="IE=edge" /> 
    <meta name="viewport" content= 
      "width=device-width, initial-scale=1.0" /> 
    <title>HTML render demo</title> 
  </head> 
  <body> 
    <h1>Home page</h1> 
  </body> 
</html> 
JavaScript

products.html

<!DOCTYPE html> 
<html lang="en"> 
  <head> 
    <meta charset="UTF-8" /> 
    <meta http-equiv="X-UA-Compatible" content="IE=edge" /> 
    <meta name="viewport" content= 
      "width=device-width, initial-scale=1.0" /> 
    <title>HTML render demo</title> 
  </head> 
  <body> 
    <h1>Products page</h1> 
  </body> 
</html> 
JavaScript

运行 app.js 文件,请使用以下命令:

node app.js
JavaScript

输出: 打开浏览器并进入 http://localhost:3000 ,然后手动切换到 http://localhost:3000/products ,你将看到以下输出。

Node.js 如何渲染HTML的纯文本

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册