本文介绍了将SSL添加到Node.js Koa Server?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用SSL加密我的Koa服务器.使用常规的httpServer似乎很简单,但是我不是用Koa做到这一点.有人可以帮忙吗?
I'd like to encrypt my Koa server with SSL. It seems simple enough with a regular httpServer, but I'm not how to do it with Koa. Could anyone help?
推荐答案
我偶然发现了此.使用节点程序包启动https服务器并向其传递 Koa
服务器实例 .callback()
.
I stumbled upon this. Launching an https server with the node package and passing it the Koa
server instance .callback()
does the trick.
var fs = require('fs');
var path = require('path');
var http = require('http');
var https = require('https');
var Koa = require('koa');
var server = new Koa();
// add main routes
// the following routes are for the authorisation challenges
// ... we'll come back to this shortly
var acmeRouter = require('./acme-router.js');
server
.use(acmeRouter.routes())
.use(acmeRouter.allowedMethods());
var config = {
domain: 'example.com',
http: {
port: 8989,
},
https: {
port: 7979,
options: {
key: fs.readFileSync(path.resolve(process.cwd(), 'certs/privkey.pem'), 'utf8').toString(),
cert: fs.readFileSync(path.resolve(process.cwd(), 'certs/fullchain.pem'), 'utf8').toString(),
},
},
};
let serverCallback = server.callback();
try {
var httpServer = http.createServer(serverCallback);
httpServer
.listen(config.http.port, function(err) {
if (!!err) {
console.error('HTTP server FAIL: ', err, (err && err.stack));
}
else {
console.log(`HTTP server OK: http://${config.domain}:${config.http.port}`);
}
});
}
catch (ex) {
console.error('Failed to start HTTP server\n', ex, (ex && ex.stack));
}
try {
var httpsServer = https.createServer(config.https.options, serverCallback);
httpsServer
.listen(config.https.port, function(err) {
if (!!err) {
console.error('HTTPS server FAIL: ', err, (err && err.stack));
}
else {
console.log(`HTTPS server OK: http://${config.domain}:${config.https.port}`);
}
});
}
catch (ex) {
console.error('Failed to start HTTPS server\n', ex, (ex && ex.stack));
}
module.exports = server;
这篇关于将SSL添加到Node.js Koa Server?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!