如何在节点上使用HTTPS。js使用表达/ socket . io

时间:2022-08-22 15:48:32

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

我正在尝试使用https运行我的节点服务器。我用快车和足球。

This is my code for https:

这是我的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
    });
  });
});

on my client its the following:

我的当事人是这样的:

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: Missing PFX or certificate + private key.

缺少PFX或证书+私钥。

EDIT: right now im getting

编辑:现在我明白了

Bad Request

坏的请求

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.

浏览器发送了一个服务器无法理解的请求。原因:您使用的是纯HTTP,而不是支持ssl的服务器端口。请使用HTTPS模式访问此URL。

2 个解决方案

#1


60  

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.

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

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

首先,我将创建密钥和cert文件,因此在一个目录中运行以下命令:

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

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

$ openssl genrsa 1024 > file.pem

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

在这里,您将被要求输入数据,但您可以留下空白按enter直到crs。pem生成。

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

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

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

$ openssl x509 -req -days 365 -in csr.pem -signkey file.pem -out file.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:

在我的app.js文件中我正在设置和启动服务器注意到我正在使用文件文件。pem和文件。最后一步生成的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);
});

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

然后我的公共/索引。我正在消耗服务器的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>

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.

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

#2


2  

This is how I managed to set it up with express:

这就是我用express设置它的方法:

var fs = require( 'fs' );
var app = require('express')();
var https        = require('https');
var server = https.createServer({
    key: fs.readFileSync('./test_key.key'),
    cert: fs.readFileSync('./test_cert.crt'),
    ca: fs.readFileSync('./test_ca.crt'),
    requestCert: false,
    rejectUnauthorized: false
},app);
server.listen(8080);

var io = require('socket.io').listen(server);

io.sockets.on('connection',function (socket) {
    ...
});

app.get("/", function(request, response){
    ...
})

I hope that this will save someone's time.

我希望这能挽救一个人的时间。

#1


60  

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.

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

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

首先,我将创建密钥和cert文件,因此在一个目录中运行以下命令:

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

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

$ openssl genrsa 1024 > file.pem

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

在这里,您将被要求输入数据,但您可以留下空白按enter直到crs。pem生成。

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

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

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

$ openssl x509 -req -days 365 -in csr.pem -signkey file.pem -out file.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:

在我的app.js文件中我正在设置和启动服务器注意到我正在使用文件文件。pem和文件。最后一步生成的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);
});

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

然后我的公共/索引。我正在消耗服务器的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>

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.

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

#2


2  

This is how I managed to set it up with express:

这就是我用express设置它的方法:

var fs = require( 'fs' );
var app = require('express')();
var https        = require('https');
var server = https.createServer({
    key: fs.readFileSync('./test_key.key'),
    cert: fs.readFileSync('./test_cert.crt'),
    ca: fs.readFileSync('./test_ca.crt'),
    requestCert: false,
    rejectUnauthorized: false
},app);
server.listen(8080);

var io = require('socket.io').listen(server);

io.sockets.on('connection',function (socket) {
    ...
});

app.get("/", function(request, response){
    ...
})

I hope that this will save someone's time.

我希望这能挽救一个人的时间。