2015-11-12 106 views
5

我如何使用Node.js的RESTify ver4.0.3獲取的RESTify REST API服務器支持HTTPS和HTTP

簡單的下面的代碼一樣工作,支持HTTP簡單的REST API服務器。一個例子API調用http://127.0.0.1:9898/echo/message

var restify = require('restify'); 

var server = restify.createServer({ 
    name: 'myapp', 
    version: '1.0.0' 
}); 
server.use(restify.acceptParser(server.acceptable)); 
server.use(restify.queryParser()); 
server.use(restify.bodyParser()); 

//http://127.0.0.1:9898/echo/sdasd 
server.get('/echo/:name', function (req, res, next) { 
    res.send(req.params); 
    return next(); 
}); 

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

假設我要支持HTTPS,使API調用https://127.0.0.1:9898/echo/message

如何才能做到這一點?

我注意到restify代碼變化很快,而舊版本的代碼可能不適用於最新版本。

+1

您是否檢查http://qugstart.com/blog/node-js/node-js-restify-server-with-both-http-and-https/? –

+0

謝謝。看起來不錯。我正在嘗試基於該鏈接的示例。目前有些問題。 – user781486

回答

9

要使用HTTPS,您需要一個密鑰和證書:

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

您需要啓動這兩個服務器允許HTTP和HTTPS訪問:

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

配置路由到服務器,爲兩個服務器聲明相同的路由,根據需要在HTTP和HTTPS之間重定向:

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

上面將聽取對路由/1的請求,並將其簡單地重定向到處理它的HTTPS服務器。

9

感謝來自Bas van Stein的評論,這是一個完整的工作示例。

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 folder 
     certificate: fs.readFileSync('./HTTPS.cert') 
    }; 

    // Instantiate our two servers 
    var 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 servers 
    var setup_server = function(app) { 
     function respond(req, res, next) { 
      res.send('I see you ' + req.params.name); 
     } 

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

    // Now, setup both servers in one step 
    setup_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); 
    });