获得Restify REST API服务器以同时支持HTTPS和HTTP [英] Get restify REST API server to support both HTTPS and HTTP
问题描述
我正在使用node.js restify ver4.0.3
I am using node.js restify ver4.0.3
以下简单代码可作为支持HTTP的简单REST API服务器. API调用示例为 http://127.0.0.1:9898/echo/message
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 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
Suppose I want to support HTTPS and make the API call https://127.0.0.1:9898/echo/message
这怎么办?
我注意到重新验证代码的更改非常快,使用旧版本的旧代码可能不适用于最新版本.
I noticed that restify code changes pretty fast and older code with older version may not work with the latest version.
推荐答案
要使用HTTPS,您需要一个密钥和一个证书:
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);
您将需要同时启动两个服务器以允许HTTP和HTTPS访问:
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);
});.
要配置到服务器的路由,请为两个服务器声明相同的路由,并根据需要在HTTP和HTTPS之间重定向:
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
});
以上内容侦听对路由/1
的请求,并将其重定向到处理它的HTTPS服务器.
The above listens to requests to a route /1
and simply redirects it to the HTTPS server which processes it.
这篇关于获得Restify REST API服务器以同时支持HTTPS和HTTP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!