[英]How to create an HTTPS server in Node.js?
給定 SSL 密鑰和證書,如何創建 HTTPS 服務?
Express API 文檔非常清楚地說明了這一點。
此外,此答案提供了創建自簽名證書的步驟。
我在Node.js HTTPS 文檔中添加了一些評論和片段:
var express = require('express');
var https = require('https');
var http = require('http');
var fs = require('fs');
// This line is from the Node.js HTTPS documentation.
var options = {
key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
cert: fs.readFileSync('test/fixtures/keys/agent2-cert.cert')
};
// Create a service (the app object is just a callback).
var app = express();
// Create an HTTP service.
http.createServer(app).listen(80);
// Create an HTTPS service identical to the HTTP service.
https.createServer(options, app).listen(443);
對於 Node 0.3.4 及以上一直到當前 LTS(在此編輯時為 v16), https://nodejs.org/api/https.html#httpscreateserveroptions-requestlistener包含您需要的所有示例代碼:
const https = require(`https`);
const fs = require(`fs`);
const options = {
key: fs.readFileSync(`test/fixtures/keys/agent2-key.pem`),
cert: fs.readFileSync(`test/fixtures/keys/agent2-cert.pem`)
};
https.createServer(options, (req, res) => {
res.writeHead(200);
res.end(`hello world\n`);
}).listen(8000);
請注意,如果要使用certbot工具使用 Let's Encrypt 的證書,則私鑰稱為privkey.pem
,證書稱為fullchain.pem
:
const certDir = `/etc/letsencrypt/live`;
const domain = `YourDomainName`;
const options = {
key: fs.readFileSync(`${certDir}/${domain}/privkey.pem`),
cert: fs.readFileSync(`${certDir}/${domain}/fullchain.pem`)
};
在谷歌搜索“node https”時發現了這個問題,但接受的答案中的例子很舊 - 取自當前(v0.10)版本節點的文檔,它應該是這樣的:
var https = require('https');
var fs = require('fs');
var options = {
key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
};
https.createServer(options, function (req, res) {
res.writeHead(200);
res.end("hello world\n");
}).listen(8000);
上面的答案很好,但是使用 Express 和 node 這將正常工作。
由於 express 為您創建了應用程序,因此我將在此處跳過。
var express = require('express')
, fs = require('fs')
, routes = require('./routes');
var privateKey = fs.readFileSync('cert/key.pem').toString();
var certificate = fs.readFileSync('cert/certificate.pem').toString();
// To enable HTTPS
var app = module.exports = express.createServer({key: privateKey, cert: certificate});
Node.js 中 HTTPS 服務器的最小設置是這樣的:
var https = require('https');
var fs = require('fs');
var httpsOptions = {
key: fs.readFileSync('path/to/server-key.pem'),
cert: fs.readFileSync('path/to/server-crt.pem')
};
var app = function (req, res) {
res.writeHead(200);
res.end("hello world\n");
}
https.createServer(httpsOptions, app).listen(4433);
如果您還想支持 http 請求,則只需進行以下小修改:
var http = require('http');
var https = require('https');
var fs = require('fs');
var httpsOptions = {
key: fs.readFileSync('path/to/server-key.pem'),
cert: fs.readFileSync('path/to/server-crt.pem')
};
var app = function (req, res) {
res.writeHead(200);
res.end("hello world\n");
}
http.createServer(app).listen(8888);
https.createServer(httpsOptions, app).listen(4433);
通過Greenlock.js使用 Let's Encrypt
我注意到這些答案都沒有表明將中間根 CA添加到鏈中,這里有一些零配置示例可以查看:
片段:
var options = {
// this is the private key only
key: fs.readFileSync(path.join('certs', 'my-server.key.pem'))
// this must be the fullchain (cert + intermediates)
, cert: fs.readFileSync(path.join('certs', 'my-server.crt.pem'))
// this stuff is generally only for peer certificates
//, ca: [ fs.readFileSync(path.join('certs', 'my-root-ca.crt.pem'))]
//, requestCert: false
};
var server = https.createServer(options);
var app = require('./my-express-or-connect-app').create(server);
server.on('request', app);
server.listen(443, function () {
console.log("Listening on " + server.address().address + ":" + server.address().port);
});
var insecureServer = http.createServer();
server.listen(80, function () {
console.log("Listening on " + server.address().address + ":" + server.address().port);
});
如果您不嘗試直接通過 connect 或 express 執行此操作,那么這是通常更容易的事情之一,而是讓本機https
模塊處理它,然后使用它來為您連接/express 應用程序提供服務。
此外,如果您在創建服務器時使用server.on('request', app)
而不是傳遞應用程序,它使您有機會將server
實例傳遞給一些創建連接/快速應用程序的初始化函數(如果需要)例如,在同一台服務器上通過 ssl 執行websockets )。
要讓您的應用分別在端口80
和443
上偵聽http
和https
,請執行以下操作
創建一個快遞應用:
var express = require('express');
var app = express();
express()
返回的應用程序是一個 JavaScript 函數。 它可以作為回調傳遞給 Node 的 HTTP 服務器來處理請求。 這使得使用相同的代碼庫輕松提供應用程序的 HTTP 和 HTTPS 版本。
你可以這樣做:
var express = require('express');
var https = require('https');
var http = require('http');
var fs = require('fs');
var app = express();
var options = {
key: fs.readFileSync('/path/to/key.pem'),
cert: fs.readFileSync('/path/to/cert.pem')
};
http.createServer(app).listen(80);
https.createServer(options, app).listen(443);
有關完整的詳細信息,請參閱文檔
你也可以使用 Fastify 框架來存檔:
const { readFileSync } = require('fs')
const Fastify = require('fastify')
const fastify = Fastify({
https: {
key: readFileSync('./test/asset/server.key'),
cert: readFileSync('./test/asset/server.cert')
},
logger: { level: 'debug' }
})
fastify.listen(8080)
(如果需要編寫測試,請運行openssl req -nodes -new -x509 -keyout server.key -out server.cert
來創建文件)
如果您只需要在本地進行本地開發,我已經為此任務創建了實用程序 - https://github.com/pie6k/easy-https
import { createHttpsDevServer } from 'easy-https';
async function start() {
const server = await createHttpsDevServer(
async (req, res) => {
res.statusCode = 200;
res.write('ok');
res.end();
},
{
domain: 'my-app.dev',
port: 3000,
subdomains: ['test'], // will add support for test.my-app.dev
openBrowser: true,
},
);
}
start();
它:
var path = require('path');
var express = require('express');
var app = express();
var staticPath = path.join(__dirname, '/public');
app.use(express.static(staticPath));
app.listen(8070, function() {
console.log('Server started at port 8070');
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.