當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript compression.default方法代碼示例

本文整理匯總了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;
開發者ID:ericmasiello,項目名稱:synbydesign,代碼行數:30,代碼來源:app.ts

示例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}`)
        }
    })
//.........這裏部分代碼省略.........
開發者ID:ascoders,項目名稱:wokugame,代碼行數:101,代碼來源:index.ts

示例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);
開發者ID:drejohnson,項目名稱:universal-angular2-starter,代碼行數:31,代碼來源:server.prod.ts

示例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);
    });
  });
};
開發者ID:DmitryEfimenko,項目名稱:angular2-seed-express,代碼行數:75,代碼來源:index.ts

示例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) {
開發者ID:baeeq,項目名稱:pivot,代碼行數:31,代碼來源:app.ts

示例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;
}
開發者ID:piotrwitek,項目名稱:jspm-hmr,代碼行數:75,代碼來源:jspm-hmr-server.ts


注:本文中的compression.default方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。