Javascript 如何在 Node.js 中创建 HTTPS 服务器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5998694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create an HTTPS server in Node.js?
提问by murvinlai
Given an SSL key and certificate, how does one create an HTTPS service?
给定 SSL 密钥和证书,如何创建 HTTPS 服务?
采纳答案by hvgotcodes
I found following example.
我找到了以下示例。
This works for node v0.1.94 - v0.3.1. server.setSecure()
is removed in newer versions of node.
这适用于节点 v0.1.94 - v0.3.1。server.setSecure()
在较新版本的节点中删除。
Directly from that source:
直接来自该来源:
const crypto = require('crypto'),
fs = require("fs"),
http = require("http");
var privateKey = fs.readFileSync('privatekey.pem').toString();
var certificate = fs.readFileSync('certificate.pem').toString();
var credentials = crypto.createCredentials({key: privateKey, cert: certificate});
var handler = function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
};
var server = http.createServer();
server.setSecure(credentials);
server.addListener("request", handler);
server.listen(8000);
回答by Jacob Marble
The Express API docspells this out pretty clearly.
该快递API文档相当明确阐述了这一点。
Additionally this answergives the steps to create a self-signed certificate.
此外,此答案提供了创建自签名证书的步骤。
I have added some comments and a snippet from the Node.js HTTPS documentation:
我在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);
回答by pkyeck
Found this question while googling "node https" but the example in the accepted answeris very old - taken from the docsof the current (v0.10) version of node, it should look like this:
在谷歌搜索“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);
回答by nu1silva
The above answers are good but with Express and node this will work fine.
上面的答案很好,但是使用 Express 和 node 这将正常工作。
Since express create the app for you, I'll skip that here.
由于 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});
回答by John Slegers
The minimal setup for an HTTPS server in Node.js would be something like this :
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);
If you also want to support http requests, you need to make just this small modification :
如果您还想支持 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);
回答by CoolAJ86
Update
更新
Use Let's Encrypt via Greenlock.js
通过Greenlock.js使用 Let's Encrypt
Original Post
原帖
I noticed that none of these answers show that adding a Intermediate Root CAto the chain, here are some zero-config examplesto play with to see that:
我注意到这些答案都没有表明将中间根 CA添加到链中,这里有一些零配置示例可以查看:
- https://github.com/solderjs/nodejs-ssl-example
- http://coolaj86.com/articles/how-to-create-a-csr-for-https-tls-ssl-rsa-pems/
- https://github.com/solderjs/nodejs-self-signed-certificate-example
- https://github.com/solderjs/nodejs-ssl-example
- http://coolaj86.com/articles/how-to-create-a-csr-for-https-tls-ssl-rsa-pems/
- https://github.com/solderjs/nodejs-self-signed-certificate-example
Snippet:
片段:
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);
});
This is one of those things that's often easier if you don'ttry to do it directly through connect or express, but let the native https
module handle it and then use that to serve you connect / express app.
如果您不尝试直接通过 connect 或 express 执行此操作,那么这是通常更容易的事情之一,而是让本机https
模块处理它,然后使用它来为您连接/express 应用程序提供服务。
Also, if you use server.on('request', app)
instead of passing the app when creating the server, it gives you the opportunity to pass the server
instance to some initializer function that creates the connect / express app (if you want to do websocketsover ssl on the same server, for example).
此外,如果您server.on('request', app)
在创建服务器时使用而不是传递应用程序,它使您有机会将server
实例传递给一些创建连接/快速应用程序的初始化函数(如果您想在同一台服务器上通过 ssl执行websockets,对于例子)。
回答by cmd
To enable your app to listen for both http
and https
on ports 80
and 443
respectively, do the following
要使您的应用程序分别侦听http
和https
端口80
和443
,请执行以下操作
Create an express app:
创建一个快速应用:
var express = require('express');
var app = express();
The app returned by express()
is a JavaScript function. It can be be passed to Node's HTTP servers as a callback to handle requests. This makes it easy to provide both HTTP and HTTPS versions of your app using the same code base.
返回的应用程序express()
是一个 JavaScript 函数。它可以作为回调传递给 Node 的 HTTP 服务器来处理请求。这使得使用相同的代码库轻松提供应用程序的 HTTP 和 HTTPS 版本。
You can do so as follows:
你可以这样做:
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);
For complete detail see the doc
有关完整的详细信息,请参阅文档
回答by Manuel Spigolon
You can use also archive this with the Fastify framework:
你也可以使用 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)
(and run openssl req -nodes -new -x509 -keyout server.key -out server.cert
to create the files if you need to write tests)
(openssl req -nodes -new -x509 -keyout server.key -out server.cert
如果需要编写测试,则运行以创建文件)
回答by Er Shubham Patidar
- Download rar file for openssl set up from here: https://indy.fulgan.com/SSL/openssl-0.9.8r-i386-win32-rev2.zip
- Just copy your folder in c drive.
- Create openssl.cnf file and download their content from : http://web.mit.edu/crypto/openssl.cnfopenssl.cnf can be put any where but path shoud be correct when we give in command prompt.
- Open command propmt and set openssl.cnf path C:\set OPENSSL_CONF=d:/openssl.cnf 5.Run this in cmd : C:\openssl-0.9.8r-i386-win32-rev2>openssl.exe
- Then Run OpenSSL> genrsa -des3 -out server.enc.key 1024
- Then it will ask for pass phrases : enter 4 to 11 character as your password for certificate
- Then run this Openssl>req -new -key server.enc.key -out server.csr
- Then it will ask for some details like country code state name etc. fill it freely. 10 . Then Run Openssl > rsa -in server.enc.key -out server.key
- Run this OpenSSL> x509 -req -days 365 -in server.csr -signkey server.key -out server.crt then use previous code that are on stack overflow Thanks
- 从这里下载用于 openssl 设置的 rar 文件:https: //indy.fulgan.com/SSL/openssl-0.9.8r-i386-win32-rev2.zip
- 只需将您的文件夹复制到c盘。
- 创建 openssl.cnf 文件并从以下位置下载它们的内容:http://web.mit.edu/crypto/openssl.cnfopenssl.cnf 可以放在任何地方,但当我们在命令提示符下给出时,路径应该是正确的。
- 打开命令提示并设置 openssl.cnf 路径 C:\set OPENSSL_CONF=d:/openssl.cnf 5.在 cmd 中运行:C:\openssl-0.9.8r-i386-win32-rev2>openssl.exe
- 然后运行 OpenSSL> genrsa -des3 -out server.enc.key 1024
- 然后它会要求输入密码:输入 4 到 11 个字符作为您的证书密码
- 然后运行这个 Openssl>req -new -key server.enc.key -out server.csr
- 然后它会询问一些详细信息,如国家代码州名等,随意填写。10 . 然后运行 Openssl > rsa -in server.enc.key -out server.key
- 运行此 OpenSSL> x509 -req -days 365 -in server.csr -signkey server.key -out server.crt 然后使用之前堆栈溢出的代码谢谢
回答by Irfan Shah
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');
});