如何使用Node.js创建HTTPS服务器
HTTP协议 是实现网络间平滑通信的最重要的协议之一,但在HTTP协议中,数据没有加密,因此在通信过程中可能会被窃听敏感信息,因此还有另一个版本的HTTP,即HTTPS,它在浏览器和服务器之间传输数据时进行加密。在本文中,我们将讨论如何使用Node.js创建一个HTTPS服务器。
要使用Node.js构建一个 HTTPS 服务器,我们需要一个SSL(Secure Sockets Layer)证书。我们可以在本地设备上创建一个自签名的SSL证书。首先让我们在我们的设备上创建一个SSL证书。
步骤1: 首先,我们需要生成一个自签名的证书。打开终端或git bash,并运行以下命令:
openssl req -nodes -new -x509 -keyout server.key -out server.cert
运行此命令后,我们将得到一些填写选项。我们可以使用“.”(点)将这些选项保持默认或为空。对于当前的选项,我们只填写两个选项,这对我们来说是可行的。
- 通用名称(例如服务器FQDN或您的姓名): localhost
- 电子邮件地址:
***************@********
(输入您的电子邮件)
其他选项如国家名称、州或省名称、地方名称、组织名称和组织单位名称均是自解释的,并且系统会给出它们的示例以进行帮助。
这将生成两个文件:
- server.cert :自签名证书文件。
- server.key :证书的私钥。
步骤2: 现在,让我们编写 index.html 文件。我们将创建一个表单通过POST请求将消息发送到服务器。
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>HTTPS Server</title>
</head>
<body>
<h1>Welcome to HTTPS Server</h1>
<br><br>
<h3>Enter your message</h3>
<!-- sending post request to "mssg" with
the message from the textarea -->
<form action="mssg" method="post">
<textarea name="message" id=""
cols="30" rows="10"></textarea>
<button type="submit">Send</button>
</form>
</body>
</html>
步骤3: 现在创建一个 app.js 文件。我们将在终端中使用npm来初始化项目。
npm init
我们还将安装 express 来处理服务器请求,并使用 body-parser 来接收来自POST请求的表单输入。
npm install express
npm install body-parser
项目结构:
步骤4: 现在我们将对 app.js 文件进行编码。在这个文件中,我们使用createServer()函数创建一个HTTPS服务器。我们将SSL证书的证书文件和密钥文件作为选项对象传递给createServer()函数。我们使用NodeJs中的express来处理GET和POST请求。
app.js
// Requiring in-built https for creating
// https server
const https = require("https");
// Express for handling GET and POST request
const express = require("express");
const app = express();
// Requiring file system to use local files
const fs = require("fs");
// Parsing the form of body to take
// input from forms
const bodyParser = require("body-parser");
// Configuring express to use body-parser
// as middle-ware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Get request for root of the app
app.get("/", function (req, res) {
// Sending index.html to the browser
res.sendFile(__dirname + "/index.html");
});
// Post request for geetting input from
// the form
app.post("/mssg", function (req, res) {
// Logging the form body
console.log(req.body);
// Redirecting to the root
res.redirect("/");
});
// Creating object of key and certificate
// for SSL
const options = {
key: fs.readFileSync("server.key"),
cert: fs.readFileSync("server.cert"),
};
// Creating https server by passing
// options and app object
https.createServer(options, app)
.listen(3000, function (req, res) {
console.log("Server started at port 3000");
});
步骤5: 在下面的命令中运行 node app.js 文件:
node app.js
现在打开浏览器并输入运行服务器的地址:
https://localhost:3000/
现在您将看到一个运行以HTTPS方式的网页。在文本区域中编写您的消息。
现在点击发送按钮,然后在你的控制台中查看。输出将会是:
所以,通过这种方式,我们可以使用Node.js创建一个HTTPS服务器