1. 程式人生 > >express建立https伺服器

express建立https伺服器

首先需要建立證書檔案:

$openssl genrsa -out privatekey.pem 1024

$openssl req -new -key privatekey.pem -out certrequest.csr

$openssl x509 -req -in certrequest.csr -signkey privatekey.pem -out certificate.pem

建立https:

var fs=requires('fs');
var https=requires('https');
var app=express();
var privatekey = fs.readFileSync('privatekey.pem', 'utf8');
var certificate = fs.readFileSync('certificate.pem', 'utf8');
var options={key:privatekey, cert:certificate};
var server = https.createServer(options, app);
server.listen(443);

測試:

app.get("/", function (req, res){
if (req.protocol == 'https'){
res.send('https');
}
});