当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript cookie-parser类代码示例

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


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

示例1: require

let socketHandler = require('./modules/socketHandler');

// constants
const SRC = '../../src/client';
const DIST = '../../dist/client';
const NPM = '../../node_modules';

// load certificates
require('./modules/certificateLoader').loadCertificates(path.join(__dirname, '../../certs'));

// db connection
mongoose.connect(process.env.MONGODB, { server: { socketOptions: { keepAlive: 1 } } });

// express setup
let app = express();
let myCookieParser = cookieParser();
let mongoStore = require('connect-mongo')(session.getExpressSession());
let mySession = session.getSession(mongoose.connection, mongoStore);
app.use(bodyParser.json(), myCookieParser, mySession, githubAuthentication.initialize(), githubAuthentication.session());
app.get('/auth/github', (req, res, next) => githubAuthentication.checkReturnTo(req, res, next), githubAuthentication.authenticate());
app.get('/auth/callback', githubAuthentication.callback());
app.get('/auth/logout', (req, res, next) => githubAuthentication.logout(req, res, next));

// static files
app.use('/client', express.static(path.join(__dirname, SRC)), express.static(path.join(__dirname, DIST)));
app.use('/node_modules', express.static(path.join(__dirname, NPM)));

// serve main page
app.get('/', (req, res) => pageSwitch.get(req, res, path.join(__dirname, SRC, 'login.html'), path.join(__dirname, SRC, 'main.html')));

// apis
开发者ID:thojansen,项目名称:github-seed,代码行数:31,代码来源:app.ts

示例2: 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");

  memoryStore = new expressSession.MemoryStore();

  try {
    const sessionsJSON = fs.readFileSync(`${__dirname}/../../sessions.json`, { encoding: "utf8" });
    (memoryStore as any).sessions = JSON.parse(sessionsJSON);
  } catch (err) {
    // Ignore
  }

  const sessionSettings = {
    name: "supSession",
    secret: config.server.sessionSecret,
    store: 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.get("/build", enforceAuth, serveBuildIndex);
  mainApp.get("/serverBuild", enforceAuth, serveServerBuildIndex);

  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]));
//.........这里部分代码省略.........
开发者ID:Pangoraw,项目名称:superpowers-core,代码行数:101,代码来源:start.ts

示例3: 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();

  mainApp.use(cookieParser());
  mainApp.use(handleLanguage);

  mainApp.get("/", (req, res) => { res.redirect("/hub"); });
  mainApp.get("/login", serveLoginIndex);
  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" ] });

  // Build HTTP server
  buildApp = express();

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

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

  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("SIGINT", onExit);
  process.on("message", (msg: string) => { if (msg === "stop") onExit(); });
}
开发者ID:alphafork,项目名称:Game-Engine-superpowers-core,代码行数:63,代码来源:start.ts

示例4: next

    constructor(options) {

        super();

        // In case of no options
        !options && (options = {});

        // Load default configuration
        this.config = require('../defaultServerConfig.js');

        // Set initial status
        this.status = -1;

        // Overwrite defaults
        for (let option in options)
            this.config[option] = options[option];

        // Create the express app
        this.server = express();

        // Use compression on all requests
        // @todo toggle compression with optional parameter
        //this.server.use(compression({threshold:0}));

        // Create router
        this.router = express.Router();

        // Set upload limit
        this.server.use(bodyParser.raw({
            limit: this.config.uploadLimit
        }));

        // Block libwww-perl
        this.server.use(
            (req, res, next) =>
                /libwww-perl/.test(req.get('user-agent')) ? res.status(403).end() : next());

        // Parse json api requests
        this.server.use(bodyParser.urlencoded({ extended: true }));
        this.server.use(bodyParser.json());


        // Add headers
        this.server.use((req, res, next) => {

            if (this.config.serverHeader)
                res.setHeader(
                    'Server',
                    'ZenX/' + packageInfo.version);

            res.setHeader('Connection', 'Keep-Alive');
            res.setHeader('Keep-Alive', 'timeout=15, max=100');

            return next();

        });

        // Standard middleware
        this.server.use(helmet.xssFilter());
        this.server.use(cookieParser());
        this.server.use(multipart());
        this.server.use(methodOverride());

        // Disable x-powered-by header
        this.server.disable('x-powered-by');

        // A route to be used later
        this.server.use(this.router);

        // If a static content path was provided
        if (this.config.static) {

            // Always add cache control header
            this.server.use(function(req, res, next) {

                res.setHeader("Cache-Control", "max-age=31104000, public");
                res.setHeader('Expires',
                    new Date(Date.now() + 345600000).toUTCString());

                return next();

            });

            // Serve static content
            this.server.use(
                express.static(
                    path.resolve(this.config.static)));

        }

        // Not found
        this.server.get('*', function(req, res) {

            res.writeHead(404, 'Not found');

            res.end('404: Not found');

        });

        var config = this.config;
//.........这里部分代码省略.........
开发者ID:raelgor,项目名称:zen-arena,代码行数:101,代码来源:Server.ts

示例5: express

import {DbConnection} from "./database";
import {credentials} from "./secret";
import * as bodyParser from "body-parser";
import {UserController} from "./controllers/userController";
import {LoanController} from "./controllers/loanController";
import {BookCopyController} from "./controllers/bookCopyController";

let app = express();
let api = express();
app.use("/api", api);

app.use(require("morgan")("dev"));
DbConnection.initConnection(app.get("env"));

app.set("port", process.env.PORT || 5000);
app.use(cookieParser(credentials.cookieSecret));
app.use(expressSession());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

//TODO.md: domains are deprecated and will be removed in the future,
//find an alternative
app.use(function (req, res, next) {
    console.log("heeyy it works!");
    var domain = require("domain").create();

    domain.on("error", function (err) {
        console.error("Domain error caught! \n", err.stack);
        try {
            setTimeout(function () {
                console.error("Failsafe shutdown");
开发者ID:JohanBaskovec,项目名称:libraryBackEnd,代码行数:31,代码来源:server.ts

示例6: Date

    var str: string = "\r\n" + new Date().toLocaleString() + "\r\n";
    str += JSON.stringify(err);

    fs.appendFile(SERVER + '/error.log', str);
};

//////////   Types  only/////////////
import {Request} from "express";
import {Response} from "express";
import {Express} from "express";
///////////////////////////////////////

const app:Express = express();

// configure our app to use bodyParser(it let us get the json data from a POST)
app.use(cookie());
app.use(session({
    resave: false, // don't save session if unmodified
    saveUninitialized: false, // don't create session until something stored
    secret:'somesecrettokenhere'
}));


app.use('/api',bodyParser.urlencoded({extended: true}));
app.use('/api',bodyParser.json());

app.use(express.static(WWW));

app.get('/', function(req:express.Request, res:express.Response){
    res.sendFile('indexts.html',{ 'root':WWW});
});
开发者ID:shumik-vladyslav,项目名称:DigitalSignagePlayList,代码行数:31,代码来源: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: express

////////////////////////////////////

process.on('uncaughtException', (err: Error) => {
	console.error(err)
	process.exit(1)
})
process.on('unhandledRejection', (reason: string, p: Promise<any>) => {
	console.error('Unhandled Rejection at: Promise', p, 'reason:', reason)
	process.exit(1)
})

////////////

var app = express()
app.use(cookie_parser())

////////////

app.get('/', (req, res) => {
	res.sendFile('index.html', { root: __dirname })
})
app.get('/client.js', (req, res) => {
	res.sendFile('client.js', { root: __dirname + '/..' })
})

app.get('/best-locales', best_locales_middleware)

app.get('/set-locale', (req, res) => {
	const locale: BCP47Locale | undefined = normalize_and_validate_bcp47_locale(req.query.lang)
开发者ID:Offirmo,项目名称:web-tech-experiments,代码行数:29,代码来源:express_server.ts

示例9: express

const app: express.Express = express();
app.disable('x-powered-by');
app.locals.compileDebug = false;
app.locals.cache = true;
// app.locals.pretty = '    ';
app.set('view engine', 'jade');

// Init API server
app.use(vhost(config.publicConfig.webApiHost, api(session)));

// Init static resources server
app.use(vhost(config.publicConfig.resourcesHost, resources()));

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cookieParser(config.cookiePass));
app.use(compression());

// CORS
app.use((req, res, next) => {
	res.header('Access-Control-Allow-Origin', config.publicConfig.url);
	res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
	res.header('Access-Control-Allow-Headers', 'Content-Type, csrf-token');
	res.header('Access-Control-Allow-Credentials', 'true');

	// intercept OPTIONS method
	if (req.method === 'OPTIONS') {
		res.sendStatus(200);
	} else {
		next();
	}
开发者ID:armchair-philosophy,项目名称:Misskey-Web,代码行数:31,代码来源:server.ts

示例10: async

const start = async() => {
    const app = express()

    /**
     * 日志处理
     */
    app.use(morgan('combined', {
        stream: {
            write: message => logger.error(message.trim())
        },
        skip: (req, res) => res.statusCode < 400
    }))

    /**
     * session 中间件
     */
    const RedisStore = connectRedis(expressSession)
    app.use(expressSession({
        secret: config.sessionSecret,
        cookie: {
            maxAge: config.sessionMaxAge
        },
        saveUninitialized: false,
        resave: false,
        store: new RedisStore({
            host: config.redisHostName,
            port: config.redisPort
        })
    }))

    /**
     * cookie 中间件
     */
    app.use(cookieParser(config.sessionSecret))

    /**
     * 压缩资源
     */
    app.use(compression())

    /**
     * 设置静态资源缓存
     */

        // 编译后的静态文件路径
    const builtStaticPath = process.env.NODE_ENV === 'production' ? 'built-production/static' : 'built/static'
    app.use('/static', express.static(builtStaticPath))

    /**
     * 解析请求 body
     */
    app.use('/api', bodyParser.json())
    app.use('/api', bodyParser.urlencoded({extended: true}))

    /**
     * 接口
     */

    // 等待数据库连接 ready
    try {
        await db
    } catch (error) {
        console.log('数据库连接失败', db)
    }

    app.use('/api', routes())

    /**
     * 默认输出页面模板
     */
    app.get('*', (req, res) => {
        res.set('Content-Type', 'text/html')
        res.send(templateHtml)
    })

    /**
     * 捕获应用抛出的错误
     */
    interface Error {
        status?: number
        message?: string
    }

    app.use((error: Error, req: express.Request, res: express.Response, next: express.NextFunction) => {
        res.status(error.status || 500).send({
            message: error.message
        })
        logger.error('handledError', error, {requestParam: req.body})
    })

    /**
     * 监听端口
     */
    app.listen(config.localPort, () => {
        // 开发模式弹窗,告知已重启 node 服务
        if (process.env.NODE_ENV !== 'production') {
            const notifier = require('node-notifier')
            notifier.notify(`server start on port: ${config.localPort}`)
        }
    })
//.........这里部分代码省略.........
开发者ID:ascoders,项目名称:wokugame,代码行数:101,代码来源:index.ts


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