本文整理匯總了TypeScript中express.Express.use方法的典型用法代碼示例。如果您正苦於以下問題:TypeScript Express.use方法的具體用法?TypeScript Express.use怎麽用?TypeScript Express.use使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類express.Express
的用法示例。
在下文中一共展示了Express.use方法的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。
示例1: bootstrap
public static bootstrap(app:Express)
{
console.log("=> Bootstrapping application...");
// Configure express middlewares
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(cookieParser());
app.use(cors(Config.current.cors));
// Setup routes
RoutesConfig.init(app);
}
示例2: initRoutes
export async function initRoutes(app: Express) {
console.log('Init routes...');
app.set('trust proxy', 'loopback');
app.use(compression());
app.use(bodyParser.json());
await db.init();
stats.init();
app.post('/vote', (req, res) => {
const vote: Vote = req.body;
if (isVoteValid(vote)) {
stats.addVote(vote);
db.saveVote(extend(vote, {
date: new Date(),
ip: req.ip,
userAgent: req.get('User-Agent')
})).then(oldVote => {
if (oldVote) {
stats.removeVote(oldVote);
}
});
} else {
console.log('Invalid vote', vote);
}
res.json({});
});
app.get('/stats', (_req, res) => {
res.set('Cache-Control', 'max-age=' + 1);
res.json(stats.getStats());
});
app.use(express.static('public'));
app.set('views', './server/views');
app.engine('handlebars', exphbs({ defaultLayout: 'main' }));
app.set('view engine', 'handlebars');
app.get(/^\/$|\/index.html/, (req, res) => {
renderWithClientToken('index', req, res);
});
app.get('/iframe.html', (req, res) => {
renderWithClientToken('iframe', req, res);
});
};
示例3: init
public static init(app:Express)
{
// Handle all application errors
app.use(function (err, req, res, next)
{
return res.status(500).send(err.stack);
} as ErrorRequestHandler);
}
示例4: addGenericHandler
private static addGenericHandler(app: Express) {
app.use((err: any, req: Request, res: Response, next: Function) => {
// Flush out the stack to the console
Logger.error('Unexpected error:');
console.error(err);
next(new ErrorDTO(ErrorCodes.SERVER_ERROR, 'Unknown server side error', err));
},
RenderingMWs.renderError
);
}
示例5: function
export default function (app: Express) {
app.use('/', indexRouter);
app.use('/auth', authRouter);
app.use('/api/authentication', authenticationRouter)
app.use('/api/permissions', permissionsRouter)
app.use('/api/users', usersRouter)
app.use('/api/events', eventsRouter)
}
示例6: appMiddleware
export function appMiddleware(app: Express) {
app.use(express.static(__dirname + '../../../../client/dist/'));
app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname+'../../../../client/dist/index.html'));
});
// return (req: Request, res: Response, next: NextFunction) => {
// // Serve static server only in production mode. In any other modes, treat this as a standalone API server.
// logger.log(config.environment);
// if (config.environment === ENV.prod) {
//
// res.sendFile(path.join(__dirname+'../../../../client/dist/index.html'));
// // app.use(express.static(path.join(__dirname, '../../../../client/dist/index.html')));
// }
// app.use(bodyParser.urlencoded({ extended: true }));
// app.use(bodyParser.json());
// next();
// }
}
示例7: route
public static route(app: Express) {
app.get('/api*', (req: Request, res: Response, next: NextFunction) => {
req._startTime = Date.now();
req.logged = true;
const end = res.end;
res.end = (a?: any, b?: any, c?: any) => {
res.end = end;
res.end(a, b, c);
Logger.verbose(req.method, req.url, res.statusCode, (Date.now() - req._startTime) + 'ms');
};
return next();
});
app.get('/node_modules*', (req: Request, res: Response, next: NextFunction) => {
req._startTime = Date.now();
req.logged = true;
const end = res.end;
res.end = (a?: any, b?: any, c?: any) => {
res.end = end;
res.end(a, b, c);
Logger.silly(req.method, req.url, res.statusCode, (Date.now() - req._startTime) + 'ms');
};
return next();
});
app.use((req: Request, res: Response, next: NextFunction) => {
if (req.logged === true) {
return next();
}
req._startTime = Date.now();
const end = res.end;
res.end = (a?: any, b?: any, c?: any) => {
res.end = end;
res.end(a, b, c);
Logger.debug(req.method, req.url, res.statusCode, (Date.now() - req._startTime) + 'ms');
};
return next();
});
}
示例8: route
public static route(app: Express) {
const setLocale = (req: Request, res: Response, next: Function) => {
let localePath = '';
let selectedLocale = req['locale'];
if (req.cookies && req.cookies[CookieNames.lang]) {
if (Config.Client.languages.indexOf(req.cookies[CookieNames.lang]) !== -1) {
selectedLocale = req.cookies[CookieNames.lang];
}
}
if (selectedLocale !== 'en') {
localePath = selectedLocale;
}
res.cookie(CookieNames.lang, selectedLocale);
req['localePath'] = localePath;
next();
};
const renderIndex = (req: Request, res: Response, next: Function) => {
ejs.renderFile(path.join(ProjectPath.FrontendFolder, req['localePath'], 'index.html'),
res.tpl, (err, str) => {
if (err) {
return next(new ErrorDTO(ErrorCodes.GENERAL_ERROR, err.message));
}
res.send(str);
});
};
const redirectToBase = (locale: string) => {
return (req: Request, res: Response) => {
if (Config.Client.languages.indexOf(locale) !== -1) {
res.cookie(CookieNames.lang, locale);
}
res.redirect('/?ln=' + locale);
};
};
app.use(
(req: Request, res: Response, next: NextFunction) => {
res.tpl = {};
res.tpl.user = null;
if (req.session.user) {
const user = Utils.clone(req.session.user);
delete user.password;
res.tpl.user = user;
}
res.tpl.clientConfig = Config.Client;
return next();
});
app.get(['/', '/login', '/gallery*', '/share*', '/admin', '/duplicates', '/faces', '/search*'],
AuthenticationMWs.tryAuthenticate,
setLocale,
renderIndex
);
Config.Client.languages.forEach(l => {
app.get(['/' + l + '/', '/' + l + '/login', '/' + l + '/gallery*', '/' + l + '/share*', '/' + l + '/admin', '/' + l + '/search*'],
redirectToBase(l)
);
});
const renderFile = (subDir: string = '') => {
return (req: Request, res: Response) => {
const file = path.join(ProjectPath.FrontendFolder, req['localePath'], subDir, req.params.file);
fs.exists(file, (exists: boolean) => {
if (!exists) {
return res.sendStatus(404);
}
res.sendFile(file);
});
};
};
app.get('/assets/:file(*)',
setLocale,
AuthenticationMWs.normalizePathParam('file'),
renderFile('assets'));
app.get('/:file',
setLocale,
AuthenticationMWs.normalizePathParam('file'),
renderFile());
}
示例9: require
import { Express } from "express";
import proxy = require("express-http-proxy");
const app: Express = {} as any;
app.use('/proxy', proxy('www.google.com'));
proxy('www.google.com', {});
proxy('www.google.com', {
proxyReqPathResolver: (req) => req.url,
});
proxy('www.google.com', {
limit: "10mb"
});
proxy('www.google.com', {
limit: 1024
});
proxy('www.google.com', {
proxyErrorHandler: (err, res, next) => {
switch (err && err.code) {
case 'ECONNRESET': { return res.status(405).send('504 became 405'); }
case 'ECONNREFUSED': { return res.status(200).send('gotcher back'); }
default: { next(err); }
}
},
});
示例10: serveStatic
export function serveStatic(prefix: string, app: Express) {
app.use(prefix, express.static(resolve(__dirname, process.env.IS_BUNDLE ? './app' : './docs')));
}