我是ExpressJS的新手(仅3个月(,我正在尝试进行一个项目,以获取我到目前为止所学到的知识。
我尝试编写一个模块来处理Express会话。但这似乎不起作用 - 没有错误,也没有响应。
代码是:
var express = require("express");
var session = require('express-session');
var MySQLStore = require('express-mysql-session')(session);
// MySQL Session Configuration
const mySQLSessionConfiguration = {
host: 'localhost',
port: 1234,
user: 'thisIsNotMyRealUsername',
password: 'neitherThisIsMyRealPassword',
database: 'aDatabase'
};
// Create Session
module.exports = function (){
return (session({
store: new MySQLStore(mySQLSessionConfiguration),
secret: 'LOL',
resave: true,
saveUninitialized: true
}));
};
和我的index.js文件:
app.use(require("./modules/session.js"));
//如果我直接在index.js中写下此,则该代码正常工作,但我想编写一个模块 - 我想学习。
CLI中的错误:无浏览器中的错误:没有什么,没有什么。我的意思是没有回应。保持等待
这里有什么问题。任何帮助将不胜感激。谢谢
我在示例应用程序上复制了您的方案,并在" session.js"文件
中编写了以下代码var clientsession = require('client-sessions');
module.exports = function (){
return (clientsession({
cookieName: 'session',
secret: 'secret',
duration: 30 * 60 * 1000,
activeDuration: 5 * 60 * 1000,
}));
};
然后在server.js中使用它如下:
app.use(require('./session.js'));
绝对可以找到它的工作。您可以分享您的错误日志以获取更多详细信息吗?
var cookieParser = require('cookie-parser');
var session = require('express-session');
var MySQLStore = require('express-mysql-session')(session);
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : '< MySQL username >',
password : '< MySQL password >',
database : '<your database name>'
});
connection.connect();
app.use(cookieParser());
app.use(session({
secret: 'supersecret',
resave: true,
saveUninitialized: true,
store: new mySQLStore(mysqlConnection: mysql.connection),
cookie: { maxAge: 1000 } //whatever you'd like
}));
这是我通常在Express和Express-Session中进行的方式。
我通过将"应用程序"直接传递到模块中解决了问题,而不是从模块返回会话。
固定代码看起来像这样:
// var express = require("express"); -- not required at all
var session = require('express-session');
var MySQLStore = require('express-mysql-session')(session);
// MySQL Session Configuration
const mySQLSessionConfiguration = {
host: 'localhost',
port: 1234,
user: 'thisIsNotMyRealUsername',
password: 'neitherThisIsMyRealPassword',
database: 'aDatabase'
};
// Create Session
module.exports = function (app){ // app received :D
app.use(session({ // app.use instead of return
store: new MySQLStore(mySQLSessionConfiguration),
secret: 'LOL',
resave: true,
saveUninitialized: true
}));
};
和index.js
var alpha = require("./modules/session.js")(app);