// 引入部分 const express=require('express'); const bodyParser=require('body-parser'); const cors=require("cors"); const session=require("express-session"); // const userRouter=require("./routes/user"); const fs=require('fs'); //创建web服务器 var server=express(); // server.listen(3000); var http=require('http'); var https=require('https');
//根据项目的路径导入生成的证书文件下面的key和pem是下载证书得到的 var privateKey = fs.readFileSync('key.key', 'utf8'); var certificate = fs.readFileSync('pem.pem', 'utf8'); var credentials = {key: privateKey, cert: certificate}; var httpServer = http.createServer(server); var httpsServer = https.createServer(credentials, server); //可以分别设置http、https的访问端口号 var PORT = 3000; var SSLPORT = 8080; //创建http服务器 httpServer.listen(PORT, function() { console.log('HTTP Server is running on: http://localhost:%s', PORT); }); //创建https服务器 httpsServer.listen(SSLPORT, function() { console.log('HTTPS Server is running on: https://localhost:%s', SSLPORT); }); //可以根据请求判断是http还是https server.get('/', function (req, res) { if(req.protocol === 'https') { res.status(200).send('This is https visit!'); } else { res.status(200).send('This is http visit!'); } });