关于node.js:Nodejs提供https服务

3次阅读

共计 1417 个字符,预计需要花费 4 分钟才能阅读完成。

在服务器上的接口服务可能是通过 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');

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 协定了。心愿对你有帮忙。

正文完
 0