likes
comments
collection
share

Node.js提供https服务

作者站长头像
站长
· 阅读数 18
在服务器上的接口服务可能是通过Nginx转发,如果是https协议那么监听的是443端口。当然接口服务也可以直接访问服务器端 Node.js 监听的端口如:3100,不过你需要开放服务器的防火墙端口才可以。
这篇文章介绍一下我曾遇到的问题,问什么要开启https服务?Node.js如何配置证书?Express.js如何配置证书?

Why HTTPS?

HTTPS是一种通过计算机网络进行安全通信的传输协议,经由HTTP进行通信,利用SSL/TLS建立全信道,加密数据包。HTTPS使用的主要目的是提供对网站服务器的身份认证,同时保护交换数据的隐私与完整性。

升级到HTTPS的好处

  • 对SEO更加友好
  • 解锁现代浏览器的一些高级功能(service workers,WebUSB,Bluetooth)也需要 HTTPS的支持。

不同协议资源访问限制

假如你的域名是 www.iicoom.top ,有一个前端项目跑在这个 http://www.iicoom.top 地址下,这个项目是可以访问 http://www.iicoom.top 提供的静态资源的。

但是如果前端项目跑在 https://www.iicoom.top,就无法访问 http://www.iicoom.top 提供的静态资源。

浏览器会抛出下面的错误:

[blocked] The page at 'https://www.iicoom.top'  was loaded over HTTPS but ran insecure content from 'http://www.iicoom.top': this content should also be loaded over HTTPS.

所以,我们需要把协议升级为 HTTPS。

Node.js启动https服务

官方文档

const https = require('https');
const fs = require('fs');

const options = {
  key: fs.readFileSync('key.pem'),
  cert: fs.readFileSync('cert.pem')
};

https.createServer(options, function (req, res) {
  res.writeHead(200);
  res.end("hello world\n");
}).listen(8000);
但是如果你使用了express框架,怎么做呢?

express配置https服务

const express = require('express');
const fs = require('fs');
const https = require('https');

const app = express();

app.get('/', (req, res) => {
  res.send('Hello World!');
});

const privateKey = fs.readFileSync('./cert/iicoom.key');
const certificate = fs.readFileSync('./cert/iicoom.crt');

https.createServer({
  key: privateKey,
  cert: certificate,
}, app).listen(port, () => {
  console.log(`Example app listening at http://localhost:${3100}`);
});

这样,就把网站、接口、静态资源都升级成了https协议了。希望对你有帮助。

文章首发于我的博客 《IICOOM-技术博客 Node.js提供HTTPS服务》