Skip to content Skip to sidebar Skip to footer

Get Restify Rest Api Server To Support Both Https And Http

I am using node.js restify ver4.0.3 The simple following code works as a simple REST API server that supports HTTP. An example API call is http://127.0.0.1:9898/echo/message var re

Solution 1:

To use HTTPS, you need a key and a certificate:

var https_options = {
  key: fs.readFileSync('/etc/ssl/self-signed/server.key'),
  certificate: fs.readFileSync('/etc/ssl/self-signed/server.crt')
};
var https_server = restify.createServer(https_options);

You will need to start both servers for allowing both HTTP and HTTPS access:

http_server.listen(80, function() {
   console.log('%s listening at %s', http_server.name, http_server.url);
});.
https_server.listen(443, function() {
   console.log('%s listening at %s', https_server.name, https_server.url);
});.

To configure routes to server, declare same routes for both servers, redirecting between HTTP and HTTPS as needed:

http_server.get('/1', function (req, res, next) {
    res.redirect('https://www.foo.com/1', next);
});
https_server.get('/1', function (req, res, next) {
    // Process the request   
});

The above listens to requests to a route /1 and simply redirects it to the HTTPS server which processes it.

Solution 2:

Thanks to the comment from Bas van Stein, here is a complete working example.

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

    // Setup some https server options//generated from http://www.selfsignedcertificate.com/var https_options = {
        key: fs.readFileSync('./HTTPS.key'), //on current foldercertificate: fs.readFileSync('./HTTPS.cert')
    };

    // Instantiate our two serversvar server = restify.createServer();
    var https_server = restify.createServer(https_options);

    // Put any routing, response, etc. logic here. This allows us to define these functions// only once, and it will be re-used on both the HTTP and HTTPs serversvar setup_server = function(app) {
        functionrespond(req, res, next) {
            res.send('I see you ' + req.params.name);
        }

        // Routes
        app.get('/test/:name', respond);
    }

    // Now, setup both servers in one stepsetup_server(server);
    setup_server(https_server);

    // Start our servers to listen on the appropriate ports
    server.listen(9848, function() {
        console.log('%s listening at %s', server.name, server.url);
    });

    https_server.listen(443, function() {
        console.log('%s listening at %s', https_server.name, https_server.url);
    });

Post a Comment for "Get Restify Rest Api Server To Support Both Https And Http"