如何使用 Express/Socket.io 在 Node.js 上使用 HTTPS [英] How to use HTTPS on Node.js using Express/Socket.io

查看:38
本文介绍了如何使用 Express/Socket.io 在 Node.js 上使用 HTTPS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Im trying to run my node server with https. I'm using express and socket.io.

这是我的 https 代码:

This is my code for 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
    });
  });
});

在我的客户端上如下:

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);

});

现在我的服务器出现以下异常:

Right now im getting the following exception on my server:

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

uncaughtException: Missing PFX or certificate + private key.

现在我得到

错误请求

您的浏览器发送了此服务器无法理解的请求.原因:您对启用 SSL 的服务器端口使用纯 HTTP.请改用 HTTPS 方案访问此 URL.

Your browser sent a request that this server could not understand. Reason: You're speaking plain HTTP to an SSL-enabled server port. Instead use the HTTPS scheme to access this URL, please.

推荐答案

如果没有您的密钥和证书文件,很难测试您的示例,相反,我将提供一个使用 Express、socket.io 和 https 的示例.

It is hard to test your example without your key and cert files instead I am going to provide an example where I am using Express, socket.io, and https.

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

First I will create the key and cert files, so inside a directory run the following commands from your terminal:

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

The command below it is going to generate a file containing an RSA key.

$ openssl genrsa 1024 > file.pem

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

Here you will be asked to input data but you can leave blank pressing enter until the crs.pem is generated.

$ openssl req -new -key file.pem -out csr.pem

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

Then a file.crt file will be created containing an SSL certificate.

$ openssl x509 -req -days 365 -in csr.pem -signkey file.pem -out file.crt

<小时>

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


So in my app.js file where I am setting and starting the server notice that I am using the files file.pem and file.crt generated in the last step:

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);
});

然后是我使用服务器的 public/index.html:

and then my public/index.html where I am consuming the server:

<!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>

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

then finally if you access from the browser at https://localhost, you will see an alert with a message that is coming from the websocket server.

这篇关于如何使用 Express/Socket.io 在 Node.js 上使用 HTTPS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆