如何为express.js服务器设置SSL证书?

mur*_*lai 122 ssl-certificate node.js express

之前,在较旧版本的express中,我可以这样做:

express.createServer({key:'keyFile', cert:'certFile'});
Run Code Online (Sandbox Code Playgroud)

但是,在较新版本的Express中,这不再有效:

var app = express();
Run Code Online (Sandbox Code Playgroud)

我应该打电话app.use()来设置证书吗?如果是这样的话?

ebo*_*man 138

请参阅Express文档以及https.createServerNode文档(这是express建议使用的):

var privateKey = fs.readFileSync( 'privatekey.pem' );
var certificate = fs.readFileSync( 'certificate.pem' );

https.createServer({
    key: privateKey,
    cert: certificate
}, app).listen(port);
Run Code Online (Sandbox Code Playgroud)

createServer的其他选项位于:http://nodejs.org/api/tls.html#tls_tls_createserver_options_secureconnectionlistener

  • @Qix - 在OPs示例中,定义了`app`.这个答案令人满意. (10认同)
  • 有没有概述如何获取.pem文件?我的证书提供商提供了两个.crt文件. (4认同)
  • 看一下`connect.js`中`createServer`的定义(express只是从connect继承了这个)。您会看到它返回一个具有正确签名的函数。`connect()` 只是 `connect.createServer()` 的别名,因此 `express()` 也是如此(它可能做了一些额外的初始化,但结果仍然是一个适合用作请求处理程序的函数)。 (2认同)

geo*_*eak 95

我能够使用以下样板代码获取SSL:

var fs = require('fs'),
    http = require('http'),
    https = require('https'),
    express = require('express');

var port = 8000;

var options = {
    key: fs.readFileSync('./ssl/privatekey.pem'),
    cert: fs.readFileSync('./ssl/certificate.pem'),
};

var app = express();

var server = https.createServer(options, app).listen(port, function(){
  console.log("Express server listening on port " + port);
});

app.get('/', function (req, res) {
    res.writeHead(200);
    res.end("hello world\n");
});
Run Code Online (Sandbox Code Playgroud)

  • 这是为时已晚,但SSL_PROTOCOL_ERROR可能是由于您使用的是http:// <ssl_enabled_endpoint>.它应该是https:// <ssl_enabled_endpoint> (6认同)
  • 您如何在浏览器上实际看到 hello world?https://127.0.0.1:8000/ 给我一个错误 107 (net::ERR_SSL_PROTOCOL_ERROR): SSL 协议错误。 (2认同)

hoo*_*ogw 8

这是我为Express 4.0 工作的代码.

express 4.0与3.0和其他版本非常不同.

4.0你有/ bin/www文件,你打算在这里添加https.

"npm start"是启动express 4.0服务器的标准方式.

readFileSync()函数应该使用__dirname获取当前目录

而require()使用./引用当前目录.

首先将private.key和public.cert文件放在/ bin文件夹下,它与WWW文件是同一个文件夹.

找不到这样的目录错误:

  key: fs.readFileSync('../private.key'),

  cert: fs.readFileSync('../public.cert')
Run Code Online (Sandbox Code Playgroud)

错误,找不到这样的目录

  key: fs.readFileSync('./private.key'),

  cert: fs.readFileSync('./public.cert')
Run Code Online (Sandbox Code Playgroud)

工作代码应该是

key: fs.readFileSync(__dirname + '/private.key', 'utf8'),

cert: fs.readFileSync(__dirname + '/public.cert', 'utf8')
Run Code Online (Sandbox Code Playgroud)

完整的https代码是:

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

// readFileSync function must use __dirname get current directory
// require use ./ refer to current directory.

const options = {
   key: fs.readFileSync(__dirname + '/private.key', 'utf8'),
  cert: fs.readFileSync(__dirname + '/public.cert', 'utf8')
};


 // Create HTTPs server.

 var server = https.createServer(options, app);
Run Code Online (Sandbox Code Playgroud)