var plug_express = require('express');
var fs = require('fs');
var http = require('http');
var https = require('https');
var app = plug_express();
var PORT = 80;
var SSLPORT = 443;
app.set('port', SSLPORT);
// 登录网站
app.get('/', function(req, res, next) {
let host = req.headers.host;
host = host.replace(/\:\d+$/, '');
if (!req.cookies.token || req.cookies.token == '0' || req.cookies.token == 'null') {
if (req.protocol === 'https') {
return res.redirect(`/login`);
} else {
if (SSLPORT == 443) {
return res.redirect(307, `https://${host}/login`);
} else {
return res.redirect(307, `https://${host}:${SSLPORT}/login`);
}
}
} else {
if (req.protocol === 'https') {
return res.redirect(`/sa_sec/main_page`);
} else {
if (SSLPORT == 443) {
return res.redirect(307, `https://${host}/sa_sec/main_page`);
} else {
return res.redirect(307, `https://${host}:${SSLPORT}/sa_sec/main_page`);
}
}
}
next()
});
function func_startHTTP() {
var httpServer = http.createServer(app);
httpServer.listen(PORT, '0.0.0.0', function() {
console.log('HTTP Server is running on: http://localhost:%s', PORT);
});
// httpApp.get('/', function(req, res, next) {
// if (req.protocol == 'http') {
// let host = req.headers.host;
// host = host.replace(/\:\d+$/, ''); // Remove port number
// res.redirect(302, `
// https: //${host}${req.path}`);
// }
// });
// if (req.protocol == 'http') {
// let host = req.headers.host;
// host = host.replace(/\:\d+$/, ''); // Remove port number
// res.redirect(302, `https://${host}${req.path}`);
// }
// app.get('/', function(req, res, next) {
// let host = req.headers.host;
// host = host.replace(/\:\d+$/, ''); // Remove port number
// res.redirect(`https://${host}${req.path}`);
// });
// app.all("*", (req, res, next) => {
// let host = req.headers.host;
// host = host.replace(/\:\d+$/, ''); // Remove port number
// res.redirect(307, `https://${host}${req.path}`);
// });
}
// 开启HTTPS服务
function func_startHTTPS() {
//TODO
var privateKey = fs.readFileSync('./static/cert/server.key', 'utf8');
var certificate = fs.readFileSync('./static/cert/server.crt', 'utf8');
var credentials = { key: privateKey, cert: certificate };
var httpsServer = https.createServer(credentials, app);
httpsServer.listen(app.get('port'), '0.0.0.0', function() {
console.log('HTTPS Server is running on: https://localhost:%s', app.get('port'));
});
httpsServer.on('error', (e) => {
console.error(e);
});
//404
app.get('*', function(req, res, next) {
var key = req.url;
console.log(key.substr(1, 13))
//TODO
if (!~~~) {
res.redirect('/404');
}
next()
});
}
function startServer() {
func_startHTTP();
func_startHTTPS();
}
startServer();
nodejs:搭建express 服务,http服务重定向到https服务
最新推荐文章于 2023-11-14 18:53:10 发布