MST

星途 面试题库

面试题:Node.js中Express框架如何配置HTTPS以提升安全性

在Node.js的Express应用中,描述配置HTTPS的步骤,包括获取SSL证书的方式(可以提及自签名证书)以及如何在Express应用中启用HTTPS服务。
18.2万 热度难度
前端开发Node.js

知识考点

AI 面试

面试题答案

一键面试
  1. 获取SSL证书
    • 购买证书:从正规的证书颁发机构(CA)如Let's Encrypt、Comodo等购买SSL证书。这些证书被广泛信任,适用于生产环境。
    • 自签名证书
      • 生成私钥:使用OpenSSL工具,在终端运行openssl genrsa -out key.pem 2048,这会生成一个2048位的私钥文件key.pem
      • 生成证书签名请求(CSR):运行openssl req -new -key key.pem -out csr.pem,按照提示输入相关信息,如国家、组织等,生成csr.pem文件。
      • 自签名证书:运行openssl x509 -req -days 365 -in csr.pem -signkey key.pem -out cert.pem,生成有效期为365天的自签名证书cert.pem。自签名证书在开发和测试环境中使用方便,但不会被浏览器默认信任。
  2. 在Express应用中启用HTTPS服务
    • 首先确保已安装expresshttps模块。如果没有安装express,运行npm install expresshttps是Node.js内置模块无需安装。
    • 编写以下代码示例:
const express = require('express');
const https = require('https');
const fs = require('fs');

const app = express();

// 引入自签名证书或购买的证书相关文件路径
const privateKey = fs.readFileSync('key.pem', 'utf8');
const certificate = fs.readFileSync('cert.pem', 'utf8');
const credentials = { key: privateKey, cert: certificate };

app.get('/', (req, res) => {
    res.send('Hello, this is an HTTPS - enabled Express app!');
});

const httpsServer = https.createServer(credentials, app);

const port = 443;
httpsServer.listen(port, () => {
    console.log(`HTTPS server running on port ${port}`);
});

在上述代码中,通过fs模块读取证书和私钥文件,然后使用https.createServer方法创建HTTPS服务器,并将Express应用作为回调函数传入。最后监听指定端口(通常是443)启动HTTPS服务。