• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

TypeScript express-session类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了TypeScript中express-session的典型用法代码示例。如果您正苦于以下问题:TypeScript express-session类的具体用法?TypeScript express-session怎么用?TypeScript express-session使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了express-session类的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的TypeScript代码示例。

示例1: express

import { DKYSessionHandler } from "./session";
import * as session from "express-session";
import { logger, errorLogger } from "./logger";

var app: express.Application = express();

app.use(logger());

app.use(helmet());

//app.use(DKYSessionHandler());

app.use(session({
    name: 'app.sid',
    secret: "1234567890QWERTY",
    resave: true,
    store: new session.MemoryStore(),
    saveUninitialized: true
}));

app.use(bodyParser.urlencoded({ extended: true }));

app.use(bodyParser.json());

app.use(methodOverride());

app.use(express.static(__dirname + "/../public"));

app.use("/", router());

app.use(errorLogger());
开发者ID:nicholas-robson,项目名称:dkydev_webapp,代码行数:31,代码来源:app.ts


示例2: express

import * as express from 'express';
import * as mongoose from 'mongoose';
import * as session from 'express-session';
import * as connectMongo from 'connect-mongo';
import * as mongodb from 'mongodb';

var app = express();

/// Create MongoStore
var MongoStore = connectMongo(session);

/// Use MongoStore

// MongoUrlOptions
app.use(session({
    secret: 'secret',
    store: new MongoStore({url: 'mongodb://localhost/test'})
}));


app.use(session({
    secret: 'secret',
    store: new MongoStore({
        url: 'mongodb://localhost/test',
        collection: "test-sessions",
        ttl: 30 * 24 * 60 * 60 // = 30 days
    })
}));

// MongooseConnectionOptions
mongoose.connect('mongodb://localhost/test')
app.use(session({
开发者ID:AbraaoAlves,项目名称:DefinitelyTyped,代码行数:32,代码来源:connect-mongo-tests.ts


示例3: Routes

var RDBStore = require('session-rethinkdb')(session);
var RDBStoreOptions = _.merge({}, dbConfig, { cleanupInterval: 5000 });
var sessionStore = { store: new RDBStore(RDBStoreOptions) };

process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var clientBaseUrl = require('config').get('clientBaseUrl');
var port = process.env.PORT || 3333;
var app = express();
var server = http.Server(app);
var io = require('socket.io')(server);

winstonConfiguration();
app.use(cookieParser());
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.use(session(_.merge({}, sessionConfig, sessionStore)));
app.use(cors());

app.use(express.static(path.join(__dirname, 'public')));

new Routes(app, express.Router());
new Sockets(io);

game.register();
category.register();

server.listen(port, function() {
  winston.info('listening on port:' + port + '; NODE_ENV='+ process.env.NODE_ENV);
});

function winstonConfiguration() {
开发者ID:radotzki,项目名称:bullshit-server,代码行数:31,代码来源:app.ts


示例4: express

import * as routes from './routes/index';

const app = express();

// view engine setup

app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({
  secret: 'somesecret',
  resave: true,
  saveUninitialized: true
}));
app.use(express.static(path.join(__dirname, '../public')));
app.use('/lib',express.static(path.join(__dirname, '../node_modules')));
app.use('/app',express.static(path.join(__dirname, '../app')));
app.use('/css',express.static(path.join(__dirname, '../public/assets/css')));
app.use('/js',express.static(path.join(__dirname, '../public/assets/js')));
app.use('/config',express.static(path.join(__dirname, '../config')));

app.use('/', routes);

let port: number = process.env.PORT || 3000;

let server = app.listen(port, function() {
    let host = server.address().address;
开发者ID:delpiero22,项目名称:KM-RAOT,代码行数:31,代码来源:server.ts


示例5: join

// Faster server renders w/ Prod mode (dev mode never needed)
enableProdMode();

// Config
const CONFIG_FOLDER = join(process.cwd(), 'config');
const config = require(join(CONFIG_FOLDER, 'amazon.json'));

// Express server
const app = express();

// Basic express session
app.use(
  session({
    secret: config.session.secret,
    saveUninitialized: false,
    resave: true
  })
);

// For jwt token errors
app.use((err, req, res, next) => {
  if (err.name === 'StatusError') {
    res.send(err.status, err.message);
  } else {
    next(err);
  }
});

const jwtCheck = jwtExpress({
  secret: config.jwt.secret
开发者ID:sumanbh,项目名称:amazon-clone,代码行数:30,代码来源:server.ts


示例6: require

//custom module import
let index : express.Router  = require('./routes/indexRoute');

//server configuration
let app   : express.Express = express();
let port  : number          = process.env.PORT || 3000;
mongoose.connect('mongodb://localhost/quiz-app');

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

//builtin middleware
app.use(express.static(path.join(__dirname, '../public')));

//third party middleware
app.use(morgan('dev'));
app.use(cookieParser('fulloffunwithcodingjsints'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(session({secret: 'fulloffunwithcodingjsints'}));
app.use(flash());

//custom mounted middleware for routing
app.use('/', index);

//start server
app.listen(port, () => {
  console.log('Express started on Port : ' + port);
});
开发者ID:asimbhai,项目名称:quiz-app,代码行数:30,代码来源:server.ts


示例7: done

        .then((app) => {
            app.set('view options', {pretty: false});
            app.set("etag", false);
            app.disable("x-powered-by");

            app.engine("dust", cons.dust);

            app.set("views", __dirname + "/../views");
            app.set("view engine", "dust");

            app.use(express.static(__dirname + "/../public"));

            passport.use(new LocalStrategy(
                function(username, password, done) {
                    storageManager.getAccountByEmail(username)
                        .then((account:any) => {
                            if (account === null) {
                                return done(null, false, { message: 'Incorrect account.' });
                            }
                            if (compareSync(password, account.password)) {
                                return done(null, account);
                            }
                            return done(null, false, { message: 'Incorrect password.' });
                        })
                        .catch((err:any) => {
                            console.log(err);
                            return done(null, false, { message: 'Internal error.' });
                        });
                }
            ));

            passport.serializeUser(function(account, done) {
                done(null, account.id);
            });

            passport.deserializeUser(function(id, done) {
                storageManager.getAccountById(id)
                    .then((account:any) => {
                        if (account !== undefined) {
                            return done(null, account);
                        }
                        return done(new Error("Invalid account"), null)
                    })
                    .catch((err:any) => {
                        done(err, null);
                    });
            });

            app.use(methodOverride());
            app.use(bodyParser.json());
            app.use(bodyParser.urlencoded({extended: false}));

            app.use(cookieParser());
            app.use(session({ secret: 'keyboard cat' }));
            app.use(passport.initialize());
            app.use(passport.session());

            app.use(flash());

            app.use((req:express.Request, res:express.Response, next:express.NextFunction) => {
                logger.info({method: req.method, url: req.url, protocol: req.protocol, ip: req.ip, hostname: req.hostname}, req.method + " " + req.path);
                next();
            });

            return app;
        });
开发者ID:JesseDavid,项目名称:express-typescript-sequelize,代码行数:66,代码来源:index.ts


示例8: start

export default function start(serverDataPath: string) {
  dataPath = serverDataPath;
  SupCore.log(`Using data from ${dataPath}.`);
  process.on("uncaughtException", onUncaughtException);

  loadConfig();

  const { version, superpowers: { appApiVersion: appApiVersion } } = JSON.parse(fs.readFileSync(`${__dirname}/../../package.json`, { encoding: "utf8" }));
  SupCore.log(`Server v${version} starting...`);
  fs.writeFileSync(`${__dirname}/../../public/superpowers.json`, JSON.stringify({ version, appApiVersion, hasPassword: config.server.password.length !== 0 }, null, 2));

  // SupCore
  (global as any).SupCore = SupCore;
  SupCore.systemsPath = path.join(dataPath, "systems");

  // List available languages
  languageIds = fs.readdirSync(`${__dirname}/../../public/locales`);
  languageIds.unshift("none");

  // Main HTTP server
  mainApp = express();

  if (typeof config.server.sessionSecret !== "string") throw new Error("serverConfig.sessionSecret is null");
  const sessionSettings = {
    name: "supSession",
    secret: config.server.sessionSecret,
    store: new expressSession.MemoryStore(),
    resave: false,
    saveUninitialized: false,
    cookie: { maxAge: 1000 * 60 * 60 * 24 * 30 }
  };

  mainApp.use(cookieParser());
  mainApp.use(bodyParser.urlencoded({ extended: false }));
  mainApp.use(handleLanguage);
  mainApp.use(expressSession(sessionSettings));
  mainApp.use(passportMiddleware.initialize());
  mainApp.use(passportMiddleware.session());

  mainApp.get("/", (req, res) => { res.redirect("/hub"); });

  mainApp.post("/login", ensurePasswordFieldIsntEmpty, passportMiddleware.authenticate("local", { successReturnToOrRedirect: "/", failureRedirect: "/login" }));
  mainApp.get("/login", serveLoginIndex);
  mainApp.get("/logout", (req, res) => { req.logout(); res.redirect("/"); });

  mainApp.get("/hub", enforceAuth, serveHubIndex);
  mainApp.get("/project", enforceAuth, serveProjectIndex);

  mainApp.use("/projects/:projectId/*", serveProjectWildcard);
  mainApp.use("/", express.static(`${__dirname}/../../public`));

  mainHttpServer = http.createServer(mainApp);
  mainHttpServer.on("error", onHttpServerError.bind(null, config.server.mainPort));

  io = socketio(mainHttpServer, { transports: [ "websocket" ] });
  io.use(passportSocketIo.authorize({
    cookieParser: cookieParser,
    key: sessionSettings.name,
    secret: sessionSettings.secret,
    store: sessionSettings.store
  }));

  // Build HTTP server
  buildApp = express();

  buildApp.get("/", redirectToHub);
  buildApp.get("/systems/:systemId/SupCore.js", serveSystemSupCore);

  buildApp.use("/", express.static(`${__dirname}/../../public`));

  buildApp.use((req, res, next) => {
    const originValue = req.get("origin");
    if (originValue == null) { next(); return; }

    const origin = url.parse(originValue);
    if (origin.hostname === req.hostname && origin.port === config.server.mainPort.toString()) {
      res.header("Access-Control-Allow-Origin", originValue);
    }
    next();
  });

  buildApp.get("/builds/:projectId/:buildId/*", (req, res) => {
    const projectServer = hub.serversById[req.params.projectId];
    if (projectServer == null) { res.status(404).end("No such project"); return; }
    let buildId = req.params.buildId as string;
    if (buildId === "latest") buildId = (projectServer.nextBuildId - 1).toString();
    res.sendFile(path.join(projectServer.buildsPath, buildId, req.params[0]));
  });

  buildHttpServer = http.createServer(buildApp);
  buildHttpServer.on("error", onHttpServerError.bind(null, config.server.buildPort));

  loadSystems(mainApp, buildApp, onSystemsLoaded);

  // Save on exit and handle crashes
  process.on("SIGTERM", onExit);
  process.on("SIGINT", onExit);
  process.on("message", (msg: string) => { if (msg === "stop") onExit(); });
}
开发者ID:defc0n1,项目名称:superpowers-core,代码行数:99,代码来源:start.ts


示例9: cookieParser

app.middleware('parse', bodyParser.json());

// to support URL-encoded bodies
app.middleware('parse', bodyParser.urlencoded({
  extended: true,
}));

// The access token is only available after boot
app.middleware('auth', loopback.token({
  model: app.models.accessToken,
}));

app.middleware('session:before', cookieParser(app.get('cookieSecret')));
app.middleware('session', expressSession({
  secret: 'kitty',
  saveUninitialized: true,
  resave: true,
  store: new mongoStore({url: 'mongodb://localhost:27017/projecty'}),
}));

passportConfigurator.init();

// We need flash messages to see passport errors
app.use(expressFlash());

passportConfigurator.setupModels({
  userModel: app.models.user,
  userIdentityModel: app.models.userIdentity,
  userCredentialModel: app.models.userCredential,
});

for (var s in config) {
开发者ID:fastegg,项目名称:projectY,代码行数:32,代码来源:server.ts


示例10: SequelizeStore

  TWITTER_CONSUMER_KEY,
  TWITTER_CONSUMER_SECRET,
} = process.env;

app.use(cors({
  origin: FRONTEND_URL,
  credentials: true
}));

const sessionStore = new SequelizeStore({db: sequelize})
sessionStore.sync()

app.use(session({
  secret: SESSION_SECRET,
  store: sessionStore,
  cookie: {
    maxAge: 7 * 24 * 60 * 60 * 1000 // 7 days
  }
}))

app.use(passport.initialize());
app.use(passport.session());

passport.serializeUser((user, done) => {
  done(null, user.id)
});
passport.deserializeUser(async (id, done) => {
  try {
    done(null, await User.findById(id))
  } catch (e) {
    done(e, null);
开发者ID:sketchglass,项目名称:respass,代码行数:31,代码来源:auth.ts



注:本文中的express-session类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
TypeScript extend类代码示例发布时间:2022-05-28
下一篇:
TypeScript express-jwt类代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap