如何使用 Express 发送 HTML 文件

介绍

Node.jsExpress应用程序中,可以使用 res.sendFile()来交付文件。

<$>[注] 注: 在表达 4.8.0 之前,支持了 res.sendfile()。此下级版本的 res.sendFile() 已被删除。

在本文中,您将学习如何使用res.sendFile()

前提条件

要完成本教程,您将需要:

本教程已通过 Node v16.0.0、npm v7.11.1 和 express v4.17.1 进行验证。

步骤1 - 设置项目

首先,打开终端窗口并创建一个新的项目目录:

1mkdir express-sendfile-example

然后,导航到新创建的目录:

1cd express-sendfile-example

在此时刻,您可以启动一个新的 npm 项目:

1npm init -y

接下来,您需要安装快递包:

1npm install [email protected]

在此时刻,你有一个新的项目准备使用Express。

创建一个新的 server.js 文件,并使用代码编辑器打开它:

 1[label server.js]
 2const express = require('express');
 3
 4const app = express();
 5const port = process.env.PORT || 8080;
 6
 7// sendFile will go here
 8
 9app.listen(port);
10console.log('Server started at http://localhost:' + port);

查看您的终端窗口并运行您的应用程序:

1node server.js

验证您的项目按预期工作后,您可以使用res.sendFile()

步骤 2 – 使用res.sendFile()

用代码编辑器修复 server.js 并添加 path, .get()res.sendFile():

 1[label server.js]
 2const express = require('express');
 3const path = require('path');
 4
 5const app = express();
 6const port = process.env.PORT || 8080;
 7
 8// sendFile will go here
 9app.get('/', function(req, res) {
10  res.sendFile(path.join(__dirname, '/index.html'));
11});
12
13app.listen(port);
14console.log('Server started at http://localhost:' + port);

当向服务器提出请求时,将提供一个index.html文件。

创建一个新的 index.html 文件,并使用代码编辑器打开它:

 1[label index.html]
 2<!DOCTYPE html>
 3<html lang="en">
 4<head>
 5  <meta charset="UTF-8">
 6  <title>Sample Site</title>
 7  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
 8  <style>
 9    body { padding-top: 50px; }
10  </style>
11</head>
12<body>
13
14  <div class="container">
15    <div class="jumbotron">
16      <h1>res.sendFile() Works!</h1>
17    </div>
18  </div>
19
20</body>
21</html>

此代码将显示消息: res.sendFile() 工作!

<$>[注] **注:**本教程使用 BootstrapCDN(https://getbootstrap.com/docs/4.3/getting-started/introduction/)来进行造型,但不需要。

保存您的更改,然后重新打开终端窗口并重新运行服务器。

1node server.js

随着服务器运行,请在 Web 浏览器中访问 http://localhost:8080:

Screenshot of index.html in a web browser displaying the message: res.sendFile() Works!

您的应用程序现在使用res.sendFile()来服务HTML文件。

结论

在本文中,您了解如何使用res.sendFile()

继续学习 学习如何使用 Express 4.0 路由器如何使用 Express 获取 URL 和 POST 参数

Published At
Categories with 技术
Tagged with
comments powered by Disqus