本文整理匯總了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
示例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]));
//.........這裏部分代碼省略.........
示例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(); });
}
示例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;
//.........這裏部分代碼省略.........
示例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");
示例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});
});
示例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;
});
示例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)
示例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();
}
示例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}`)
}
})
//.........這裏部分代碼省略.........