如何使用Express/Socket.io在Node.js上使用HTTPS

kov*_*gel 26 https node.js express socket.io

我试图用https运行我的节点服务器.我正在使用express和socket.io.

这是我的https代码:

var httpsPort = 443;
var privateKey = fs.readFileSync(mykeypath');
var certificate = fs.readFileSync(mycertificatepath');
var credentials = {key: privateKey, cert: certificate};
var https = require('https').Server(credentials,app);
var io = require('socket.io')(https);

https.listen(httpsPort, function(){
logger.info('listening on *:' + httpsPort);
});


app.get('/initGame', function (req,res){

var slots = require('./slots.json', 'utf8');
var userObject = {
    address : req.connection.remoteAddress,
    userAgent : req.headers['user-agent']
};
db.getPlayedGames(userObject,function(playedGames){
    logger.debug(playedGames);
    if(typeof playedGames == 'undefined' ){
        playedGames=0;
    }else{
        playedGames = playedGames.games_played;
    }
    var spinsLeft = 10-playedGames;
    res.json({
        spinsLeft: spinsLeft,
        slots: slots
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

在我的客户端上它的以下内容:

var myServer = "//" + document.domain + ":443";

$.get( myServer + "/initGame", function(data) {
    totalSpinsLeft = data.spinsLeft;
    $('#trysLeft').text(totalSpinsLeft);
    Seven.init(data.slots);
}).fail(function(){
    setTimeout(function(){
        $('#spinner2').text('Fehler bitte neu laden!');
    },3000);

});
Run Code Online (Sandbox Code Playgroud)

现在我在我的服务器上获得以下异常:

uncaughtException:缺少PFX或证书+私钥.

编辑:现在我得到

错误的请求

您的浏览器发送了此服务器无法理解的请求.原因:您正在向支持SSL的服务器端口说明HTTP.请使用HTTPS方案访问此URL.

Wil*_*son 71

没有你的密钥和证书文件很难测试你的例子,而是我将提供一个我使用Express,socket.io和https的例子.

首先,我将创建密钥和证书文件,因此在目录中运行终端的以下命令:

它下面的命令将生成一个包含RSA密钥的文件.

$ openssl genrsa 1024 > file.pem
Run Code Online (Sandbox Code Playgroud)

在这里,您将被要求输入数据,但您可以留空,按Enter键直到生成crs.pem.

$ openssl req -new -key file.pem -out csr.pem
Run Code Online (Sandbox Code Playgroud)

然后将创建包含SSL证书的file.crt文件.

$ openssl x509 -req -days 365 -in csr.pem -signkey file.pem -out file.crt
Run Code Online (Sandbox Code Playgroud)

因此,在我app.js设置和启动服务器的文件中file.pem,请注意我正在使用这些文件并file.crt在最后一步中生成:

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

var express = require('express');
var app = express();

var options = {
  key: fs.readFileSync('./file.pem'),
  cert: fs.readFileSync('./file.crt')
};
var serverPort = 443;

var server = https.createServer(options, app);
var io = require('socket.io')(server);

app.get('/', function(req, res) {
  res.sendFile(__dirname + '/public/index.html');
});

io.on('connection', function(socket) {
  console.log('new connection');
  socket.emit('message', 'This is a message from the dark side.');
});

server.listen(serverPort, function() {
  console.log('server up and running at %s port', serverPort);
});
Run Code Online (Sandbox Code Playgroud)

然后我public/index.html在消耗服务器的地方:

<!doctype html>
<html>

  <head>

  </head>
  <body>
    <h1>I am alive!!</h1>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.5/socket.io.js"></script>

    <script>
      var URL_SERVER = 'https://localhost:443';
      var socket = io.connect(URL_SERVER);

      socket.on('message', function(data) {
        alert(data);
      });
    </script>
  </body>

</html>
Run Code Online (Sandbox Code Playgroud)

最后,如果您从浏览器访问https://localhost,您将看到一条带有来自websocket服务器的消息的警报.

  • 不工作错误是ERR_CERT_AUTHORITY_INVALID (3认同)