liren123.cn
1.先申请SSL证书
腾讯云阿里云有免费的SSL,注意每个域名,子域名分开申请
2.www文件
var http = require('http');
var https = require('https');
var httpsPort = 443; // 自定义
var httpPort = 80; // 自定义
var port = normalizePort(process.env.PORT || httpPort);
const options = {
key:fs.readFileSync(path.join(__dirname, 'ssl','liren123.cn.key')),
cert:fs.readFileSync(path.join(__dirname, 'ssl','liren123.cn_bundle.crt')),
};
/**
* Create HTTPs server.
*/
var httpsServer = https.createServer(options,app);
httpsServer.listen(httpsPort);
console.log('https服务启动成功,请访问 https://localhost:'+httpsPort)
/**
* Create HTTP server.
*/
var server = http.createServer(app).listen(httpPort);
console.log('http服务启动成功,请访问 http://localhost:'+httpPort)
/**
* Listen on provided port, on all network interfaces.
*/
httpsServer.on('error', onError);
server.on('error', onError);
server.on('listening', onListening);
3.如果需要强制https
app.js
//此处为强制https
function requireHTTPS(req, res, next) {
if (!req.secure) {
//FYI this should work for local development as well
return res.redirect('https://' + req.get('host') + req.url);
}
next();
}
app.use(requireHTTPS);