本文整理汇总了TypeScript中compression.default方法的典型用法代码示例。如果您正苦于以下问题:TypeScript compression.default方法的具体用法?TypeScript compression.default怎么用?TypeScript compression.default使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类compression
的用法示例。
在下文中一共展示了compression.default方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1: express
import * as compression from 'compression';
import * as Sentry from '@sentry/node';
import apiRouter from './routes/api';
import uiRouter from './routes/ui';
import errorMiddleware from './middleware/errorMiddleware';
const TWO_WEEKS = 1000 * 60 * 60 * 24 * 14;
Sentry.init({
dsn: process.env.SENTRY_SERVER_DSN,
});
const app = express();
app.disable('x-powered-by'); // removes 'X-Powered-By: Express' header
app.use(Sentry.Handlers.requestHandler());
app.use(compression()); // enable gzip compression
app.set('port', process.env.PORT || 3000);
app.use(
express.static('public', {
maxAge: TWO_WEEKS,
}),
);
app.set('view engine', 'ejs');
app.use('/api', apiRouter);
app.use('*', uiRouter);
app.use(Sentry.Handlers.errorHandler());
app.use(errorMiddleware);
export default app;
示例2: 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}`)
}
})
//.........这里部分代码省略.........
示例3: express
// Application
import { App } from '../app';
const DEBUG = process.env.NODE_ENV !== 'production';
const PORT = process.env.PORT || 3000;
const app = express();
const server = http.createServer(app);
if (process.env.NODE_ENV === 'production') {
enableProdMode();
}
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(compression());
app.use(morgan(DEBUG ? 'dev' : 'combined'));
// Serve static files
app.use(express.static(CLIENT_DIR));
// Our API for demos only
app.get('/data.json', (req, res) => {
res.json({
data: 'This fake data came from the server.'
});
});
// Routes with html5pushstate
app.use('/', ngApp);
app.use('/about', ngApp);
示例4: init
export function init(port: number, mode: string) {
app.use(bodyParser.json());
app.use(compression());
/**
* Dev Mode.
* @note Dev server will only give for you middleware.
*/
if (mode == 'dev') {
app.all('/*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
routes.init(app);
let root = path.resolve(process.cwd());
let clientRoot = path.resolve(process.cwd(), './dist/dev/client')
app.use(express.static(root));
app.use(express.static(clientRoot));
var renderIndex = (req: express.Request, res: express.Response) => {
res.sendFile(path.resolve(__dirname, _clientDir + '/index.html'));
};
app.get('/*', renderIndex);
/**
* Api Routes for `Development`.
*/
}
else {
/**
* Prod Mode.
* @note Prod mod will give you static + middleware.
*/
/**
* Api Routes for `Production`.
*/
routes.init(app);
/**
* Static.
*/
app.use('/js', express.static(path.resolve(__dirname, _clientDir + '/js')));
app.use('/css', express.static(path.resolve(__dirname, _clientDir + '/css')));
app.use('/assets', express.static(path.resolve(__dirname, _clientDir + '/assets')));
/**
* Spa Res Sender.
* @param req {any}
* @param res {any}
*/
var renderIndex = function (req: express.Request, res: express.Response) {
res.sendFile(path.resolve(__dirname, _clientDir + '/index.html'));
};
/**
* Prevent server routing and use @ng2-router.
*/
app.get('/*', renderIndex);
}
/**
* Server with gzip compression.
*/
return new Promise<http.Server>((resolve, reject) => {
let server = app.listen(port, () => {
var port = server.address().port;
console.log('App is listening on port:' + port);
resolve(server);
});
});
};
示例5: addRoutes
import * as plyqlRoutes from './routes/plyql/plyql';
import * as pivotRoutes from './routes/pivot/pivot';
import * as settingsRoutes from './routes/settings/settings';
import * as mkurlRoutes from './routes/mkurl/mkurl';
import * as healthRoutes from './routes/health/health';
import { errorLayout } from './views';
var app = express();
app.disable('x-powered-by');
function addRoutes(attach: string, router: Router | Handler): void {
app.use(attach, router);
app.use(SERVER_SETTINGS.serverRoot + attach, router);
}
app.use(compress());
app.use(logger('dev'));
addRoutes('/', express.static(path.join(__dirname, '../../build/public')));
addRoutes('/', express.static(path.join(__dirname, '../../assets')));
app.use((req: PivotRequest, res: Response, next: Function) => {
req.user = null;
req.version = VERSION;
req.getSettings = (opts: GetSettingsOptions = {}) => {
return SETTINGS_MANAGER.getSettings(opts);
};
next();
});
if (AUTH) {
示例6: createServer
export function createServer(options: ServerOptions): JspmHmrServer {
// APP
const app = express();
// Apply gzip compression
app.use(compress());
// TODO: CORS
// const headers = {
// 'Access-Control-Allow-Origin': '*',
// 'Access-Control-Allow-Credentials': 'true',
// };
// Apply Proxy middleware
if (options.proxy) {
const proxyTarget = options.proxy;
const proxyRoute = options.proxyRoute || '*';
const proxyServer = httpProxy.createProxyServer();
app.use(proxyRoute, (req, res) => {
req.url = `${req.originalUrl}`;
proxyServer.web(req, res, { target: proxyTarget });
proxyServer.on('error', (err: Error) => {
console.log('Proxy Server Error: ', err.message);
});
});
}
// Apply Fallback middleware to rewrite route requests
// and serve /index.html for SPA Applications
if (options.fallback) {
const fallback = options.fallback === true ? '/index.html' : options.fallback;
console.log('history api fallback active', fallback);
app.use(historyApiFallback({
index: fallback, verbose: !!options.verbose,
}));
}
// Cache config
const cache = options.cache && options.cache * 1000 || -1;
// Server static files with cache headers
const staticRoot = options.path || '.';
console.log(`static files served from ${path.resolve(staticRoot)}`);
app.use(express.static(staticRoot, { maxAge: cache }));
// Creating NodeJS Server Instance
let serverInstance;
if (options.ssl) {
const key = options.key || Config.KEY_PATH;
const cert = options.cert || Config.CERT_PATH;
const sslOptions = (key && cert) && {
key: fs.readFileSync(key),
cert: fs.readFileSync(cert),
};
serverInstance = https.createServer(sslOptions, app);
} else {
serverInstance = http.createServer(app);
}
// Creating Chokidar Socket.io Server
if (!options.disableHmr) {
const chokidarOptions = {
...{ quiet: false, path: options.path },
app: serverInstance,
};
chokidar(chokidarOptions);
}
return serverInstance;
}