当前位置:网站首页>nodejs:搭建express 服务,设置session以及实现退出操作
nodejs:搭建express 服务,设置session以及实现退出操作
2022-07-28 10:28:00 【shunzi2016】
const plug_i18next = require('i18next');
const plug_i18nextMiddleware = require('i18next-express-middleware');
const plug_Backend = require('i18next-node-fs-backend');
var plug_express = require('express');
var plug_path = require('path');
var plug_methodOverride = require('method-override');
var plug_session = require('express-session');
var plug_cookieParser = require('cookie-parser');
var plug_multiparty = require('multiparty');
var plug_jade = require('jade');
var plug_favicon = require('serve-favicon');
var child_process = require('child_process');
var plug_errorHandler = require('errorhandler');
var plug_request = require('request');
var plug_httpproxy = require('http-proxy');
var plug_proxy = require('http-proxy-middleware');
var fs = require('fs');
var http = require('http');
var https = require('https');
var app = plug_express();
var jwt = require('jsonwebtoken'); // 使用jwt签名
var PORT = 80;
var SSLPORT = 8888;
var TimeOut = 3600;
app.set('port', SSLPORT);
app.use(plug_session({
/*可以随便写。 一个 String 类型的字符串,作为服务器端生成 session 的签名 */
secret: 'QuotPXt',
name: 'sQt_KYBGRExdetyhLMN0387650XXD',
/*保存在本地cookie的一个名字 默认connect.sid 可以不设置*/
/*强制保存 session 即使它并没有变化,。默认为 true。建议设置成 false。*/
resave: false,
/*强制将未初始化的 session 存储。 默认值是true 建议设置成true*/
saveUninitialized: true,
cookie: {
maxAge: 1000 * 30 * 60 /*过期时间*/
},
/*secure https这样的情况才可以访问cookie*/
//设置过期时间比如是30分钟,只要游览页面,30分钟没有操作的话在过期
//在每次请求时强行设置 cookie,这将重置 cookie 过期时间(默认:false)
rolling: true
}));
app.use(plug_cookieParser());
var originalFilename = "";
app.use(plug_express.static(plug_path.join(__dirname, 'static')));
app.use(plug_i18nextMiddleware.handle(plug_i18next));
//合并g_dictRootFromHeader到root中
for (var key in js_headjsonhandle.g_dictRootFromHeader) {
root[key] = js_headjsonhandle.g_dictRootFromHeader[key];
}
for (var key in root) {
if (key) {
renderCommon(key)
}
}
// 开启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);
});
function logout(req, res, next) {
new Promise((resole, rej) => {
var res_data = {};
req.session.destroy(function(err) {
console.log(err);
})
res_data.code = 0;
res_data.msg = "退出成功";
resole(res_data);
}).then((res_data) => {
if (res_data) {
return res.json(res_data);
}
});
}
//404
app.all('*', function(req, res, next) {
var key = req.url;
if (req.path == '/CE/logout') {
logout(req, res, next);
} else {
res.redirect('/404');
}
next()
});
}
// 登录网站
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);
});
}
function startServer() {
func_startHTTP();
func_startHTTPS();
}
startServer();边栏推荐
- Tensorflow knowledge points
- Yan reported an error: could not find any valid local directory for nmprivate/
- Arduino基础知识
- GKLinearCongruentialRandomSource
- Go json. Decoder Considered Harmful
- 粒子群实现最优解的求解
- Configuring raspberry pie, process and problems encountered
- QT generation Exe file and run without QT environment (enigma virtual box for green executable software packaging) graphic tutorial
- 非关系型数据库MongoDB的特点及安装
- Pyqt5 rapid development and practice 4.12 calendar and time
猜你喜欢

The future of generating confrontation networks in deepfake

Pyqt5 rapid development and practice 4.12 calendar and time

GKConstantNoiseSource

Excel word 简单 技巧 整理(持续更新 大概~)

GKCylindersNoiseSource

GKRidgedNoiseSource

7. MapReduce custom sorting implementation

SDUT Round 9 2020 Spring Festival campaign

GKConstantNoiseSource

两年CRUD,二本毕业,备战两个月面试阿里,侥幸拿下offer定级P6
随机推荐
Aike AI frontier promotion (7.28)
I don't know how lucky the boy who randomly typed logs is. There must be a lot of overtime
GKSphereObstacle
Install Office customization. Troubleshooting during installation
GKNoiseMap
Django celery redis send email asynchronously
GKConstantNoiseSource
GKNoise
Semeval 2022 | introducing knowledge into ner system, aridamo academy won the best paper award
ACM winter vacation training 5
STM32中的APB2和APB1
GKPerlinNoiseSource
Idea create my first project
Yan reports an error: exception message: /bin/bash: line 0: fg: no job control
PyQt5快速开发与实战 4.12 日历与时间
c语言进阶篇:指针(一)
8. Detailed explanation of yarn system architecture and principle
andorid 开发
GKSpheresNoiseSource
Inside story of Wu xiongang being dismissed by arm: did the establishment of a private investment company harm the interests of shareholders?