Как создать защищенный сервер Node.js с помощью `https.js`? - PullRequest
0 голосов
/ 11 сентября 2018

Попытка создать защищенный сервер для приложения nodeJs с использованием https.js модуля NPM.

app.js:

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

var cert = {
    key:     fs.readFileSync('/opt/cert/server.key.pem'),
    cert:    fs.readFileSync('/opt/cert/server.cert.pem')
};

console.log(cert);

var server = http.createServer(cert, function (req, res) {
    console.log("I am the listener!");
    res.write('Hello World!'); //write a response to the client
    res.end(); //end the response
});

server.on('error', function (e) {
    // Handle your error here
    console.log(e);
});

server.listen(3005, function(e) {
    console.log("bambam");
    console.log(e);
});

Пробовал локально и на удаленном сервере. Порт прослушивает, поскольку браузер не сообщает об отказе в соединении, но говорит, что ответа нет.

Ответы [ 2 ]

0 голосов
/ 11 сентября 2018

Не уверен, что вы делаете неправильно, возможно, вы забыли передать сертификат.

Вот мой app.js для безопасного сервера, и он работает хорошо.

app.js:

  /*jshint multistr: true, node: true, esversion: 6, undef: true, unused: true, varstmt: true*/
  "use strict";

  // NPM Modules
  const bodyParser                  = require('body-parser'),
        CORS                        = require('cors'),
        express                     = require('express'),
        FS                          = require('fs'),
        HTTPS                       = require('https'),
        path                        = require('path'),
  // Internal Modules
        console                     = require('./config/logger').log,
        router                      = require('./router');

  const app                         = express();

  // Cross-Origin Resource Sharing
  app.use(CORS());

  // configure the app to use bodyParser() to extract body from request.
  // parse urlencoded types to JSON
  app.use(bodyParser.urlencoded({
  extended: true
  }));

  // parse various different custom JSON types as JSON
  app.use(bodyParser.json({ type: 'application/*+json' }));

  // parse some custom thing into a Buffer
  app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }));

  // parse an HTML body into a string
  app.use(bodyParser.text({ type: 'text/html' }));

  // Setup views directory, file type and public filder.
  app.set('views', __dirname + '/views');
  app.set('view engine', 'ejs');
  app.use(express.static(path.join(__dirname, 'public')));

  app.use(function(req, res, next) {
        if (req.secure) {
        next();
        } else {
        res.redirect('https://' + req.headers.host + req.url);
        }
  });

  router(app);

  const port = process.env.PORT || 3000;

  console.info('server listening at https://127.0.0.1 over port: ', port);

  const key                     = FS.readFileSync( './config/encryption/private.key' ),
        cert                    = FS.readFileSync( './config/encryption/mydomain.crt' ),
        ca                      = FS.readFileSync( './config/encryption/mydomain.crt' );

  HTTPS.createServer( {key, cert, ca}, app).listen(3000);
0 голосов
/ 11 сентября 2018

попробуй так:

var http = require('http');
http.createServer(function (req, res) {
    console.log("I am the listener!");
    res.write('Hello World!'); //write a response to the client
    res.end(); //end the response
}).listen(3005);
...