在服务器上的接口服务可能是通过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协定了。心愿对你有帮忙。