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


TypeScript express.static函數代碼示例

本文整理匯總了TypeScript中express.static函數的典型用法代碼示例。如果您正苦於以下問題:TypeScript static函數的具體用法?TypeScript static怎麽用?TypeScript static使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了static函數的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。

示例1: start

function start(workingDir?: string): void {
    workingDir = workingDir || __dirname;
    // Setup
    let app = express(),
        serverPort = 3000,
        debug = true;


    // View Engine setup
    app.set('views', path.join(workingDir, 'views'));
    app.set('view engine', 'jade');

    // Configuration
    app.disable('etag'); // Disables etags for JSON requests
    // app.use(favicon(workingDir + '/public/assets/favicon.ico'));
    app.use(morgan('dev', { stream: logger.toStream() }));
    app.use(lessMiddleware(path.join(workingDir, 'public'), {
        force: true,
        debug: debug,
    }));
    app.use(bodyParser.json());
    app.use(express.static(path.join(workingDir, 'public'), { etag: true }));

    // Initialize Event Sourcing infrastructure
    esManager
        .configure(registry => {
            let serviceGroupListener = new ServiceGroupModelListener();
            registry
                .command(ServiceGroupCommands.CreateServiceGroup).handledBy(new CreateServiceGroupHandler())
                .command(ServiceGroupCommands.AddService).handledBy(new AddServiceHandler())
                .event(ServiceGroup.Events.ServiceGroupCreated).triggers(evt => serviceGroupListener.handleCreated(evt))
                .event(ServiceGroup.Events.ServiceAdded).triggers(evt => serviceGroupListener.handleServiceAdded(evt));
        })
        .start();

    // Main SPA route
    app.get('/', (req: Request, res: Response) => res.render('layout', {}));

    // APIs
    let controllers = [
        new ServiceGroupApi(),
    ];
    controllers.forEach(ctrl => app.use(ctrl.routes()));

    // Error handlers
    app.use((req: Request, res: Response, next: Function) => {
        var message = `Could not find resource: ${req.url}`,
            err = new Error(message);
        err['status'] = 404;
        next(err);
    });

    app.use((err: Error, req: Request, res: Response, next:Function) => {
        let errorId = Utils.uuid();
        res.status(err['status'] || 500);
        res.send({
            id: errorId,
            message: err.message,
            stack: debug === true ? err.stack.split('\n') : undefined
        });
    });

    // Setup server
    let port = serverPort;
    app.set('port', port);
    let server = http.createServer(app);

    logger.info(`Server listening on port ${port}`);
    server.listen(port);
    server.on('error', (error: any) => {
        if (error.syscall !== 'listen') {
            throw error;
        }

        let bind = typeof port === 'string'
            ? 'Pipe ' + port
            : 'Port ' + port;

        // Handle specific listen errors with friendly messages
        switch (error.code) {
            case 'EACCES':
                logger.error(bind + ' requires elevated privileges');
                process.exit(1);
                break;
            case 'EADDRINUSE':
                logger.error(bind + ' is already in use');
                process.exit(1);
                break;
            default:
                throw error;
        }
    });

    server.on('listening', () => {
        let addr = server.address(),
            bind = typeof addr === 'string'
                ? 'pipe ' + addr
                : 'port ' + addr.port;
        logger.info('Listening on ' + bind);
    });
//.........這裏部分代碼省略.........
開發者ID:dflor003,項目名稱:radar-radiator,代碼行數:101,代碼來源:server.ts

示例2: express

        .forEach((mod) => { console.log(Mod.parseFromJson(JSON.stringify((mod)))); });
});

let app: Express = express();

// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "jade");

// uncomment after placing your favicon in /public
// app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger("dev"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));

app.use("/", index.router);
app.use("/users", users.router);

// catch 404 and forward to error handler
app.use(function(req: Request, res: Response, next: NextFunction) {
    let err: HttpError = Error("Not Found");
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
開發者ID:phroph,項目名稱:node-factorio-launcher,代碼行數:31,代碼來源:app.ts

示例3: async

export default async (app: Application) => {
  if (config.database) {
    mongoose.connect(
      config.database.params.connection_string,
      {
        useNewUrlParser: true,
      },
    );
  }

  app.use(bodyParser.urlencoded({ extended: true }));
  app.use(bodyParser.json());

  if (config.sessions) {
    app.use(clientSessions(config.sessions));
  }

  if (config.templates) {
    app.engine(config.templates.type, (await import(config.templates.type)).default.__express);
    app.set("view engine", config.templates.type);
  }

  if (config.pages) {
    config.pages.forEach((pageConfig: IPage) => {
      app.get(pageConfig.route, (_req: IRequest, res: Response) => {
        // req.headers
        if (pageConfig.template) {
          res.render(pageConfig.template, pageConfig.parameters);
        } else {
          res.status(200).json(pageConfig.parameters);
        }
      });
    });
  }

  if (config.static) {
    app.use(expressStatic(`__dirname${config.static}`));
  }

  if (config.collections) {
    config.collections.forEach((schema: ISchema) => {
      const modelSchema = model(schema);
      app.get(`/${schema.name}`, async (_req: IRequest, res: Response) =>
        res.status(200).json(await modelSchema.find()),
      );
      app.get(`/${schema.name}/:id`, async (req: IRequest, res: Response) => {
        try {
          res.status(200).json(await modelSchema.findOne({_id: req.params.id}));
        } catch (err) {
          res.status(404).json({error: "Not Found"});
        }
      });
      app.post(`/${schema.name}`, async (req: IRequest, res: Response) => {
        try {
          const newModel = new modelSchema(req.body);
          await newModel.save();
          res.status(201).json(newModel);
        } catch (err) {
          res.status(400).json({error: err.message});
        }
      });
      /*
      app.put(`/${schema.name}/:id`, async (req: IRequest, res: Response) => {
        //
      });
      app.patch(`/${schema.name}/:id`, async (req: IRequest, res: Response) => {
        //
      });
      app.delete(`/${schema.name}/:id`, (req: IRequest, res: Response) => {
        //
      });
      */
    });
  }

  /*if (config.auth) {
    config.auth.forEach((authConfig: IAuthConfig) => {
      //
    });
  }*/
};
開發者ID:dandart,項目名稱:arsebeatfish,代碼行數:81,代碼來源:index.ts

示例4: require

        }
    }));
    app.set('views',__dirname + '/server/views/dev');
}else{
    app.set('views',__dirname + '/public/demo');
}

app.set('view engine', 'html');
app.engine('.html', require('ejs').__express)


app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(cookieParser());
app.use(express.static(__dirname+'/public'));

// Routes
app.get('/demo/index',index.index);
app.get('/demo/picker',index.index);
app.get('/demo/toast',index.index);
app.get('/demo/alert',index.index);
app.get('/demo/preloader',index.index);
app.get('/demo/indicator',index.index);
app.get('/demo/actions',index.index);
app.get('/demo/pullToRefresh',index.index);
app.get('/demo/infiniteScroll',index.index);

//錯誤處理
app.get('/*',function(req,res){
   res.writeHead(301,{
開發者ID:WeBest,項目名稱:vue-msui,代碼行數:31,代碼來源:server.ts

示例5: require

require('./api/cars/car.model');
require('./api/users/user.model');
mongoose.connect(MONGO_URL, (err) => {
    if (err) console.error(err);
    else console.log(`Connected to ${MONGO_URL}`);
});

// Render jade files for the client
// TODO: add gulp task to compile jade to html, and send back that html instead of rendering jade
app.get(/\/client.{0,}\/.+\.jade/, (req, res, next) => {
    res.render(config.root + req.path);
});

// Routes Config
app.use(require('body-parser')());
app.use('/client', express.static('client'));
app.use('/bower_components', express.static('bower_components'));

// Routes
app.get('/', (req, res, next) => {
    res.sendFile(config.client + '/index.html');
});

app.use('/api/v1/cars', require('./api/cars/car.routes'));
app.use('/api/v1/users', require('./api/users/user.routes'));

// if path starts with /client, /bower_components, or /api, send a 404
app.get(/\/(client|bower_components|api).{0,}/, (req, res, next) => {
    next({ status: 404, message: `${req.path} is not found, or does not exist. Please check for typos.` });
});
開發者ID:UtopianOwl,項目名稱:dcproj,代碼行數:30,代碼來源:server.ts

示例6: Server

const gameServer = new Server({
  // engine: WebSocket.Server,
  server: server
});

// Register ChatRoom as "chat"
gameServer.register("chat", ChatRoom).then((handler) => {
  // demonstrating public events.
  handler.
    on("create", (room) => console.log("room created!", room.roomId)).
    on("join", (room, client) => console.log("client", client.id, "joined", room.roomId)).
    on("leave", (room, client) => console.log("client", client.id, "left", room.roomId)).
    on("dispose", (room) => console.log("room disposed!", room.roomId));
})

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

app.get("/something", (req, res) => {
  console.log("something!", process.pid);
  console.log("GET /something")
  res.send("Hey!");
});

app.post("/something", (req, res) => {
  console.log("POST /something")
  res.json(req.body);
});

gameServer.onShutdown(() => {
  console.log("CUSTOM SHUTDOWN ROUTINE: STARTED");
  return new Promise((resolve, reject) => {
開發者ID:cymbiotica,項目名稱:colyseus,代碼行數:31,代碼來源:Server.ts

示例7: ngExpressEngine

// Import module map for lazy loading
import { provideModuleMap } from '@nguniversal/module-map-ngfactory-loader';

app.engine('html', ngExpressEngine({
  bootstrap: AppServerModuleNgFactory,
  providers: [
    provideModuleMap(LAZY_MODULE_MAP)
  ]
}));

app.set('view engine', 'html');
app.set('views', join(DIST_FOLDER, 'browser'));

// TODO: implement data requests securely
app.get('/api/*', (req, res) => {
  res.status(404).send('data requests are not supported');
});

// Server static files from /browser
app.get('*.*', express.static(join(DIST_FOLDER, 'browser')));

// All regular routes use the Universal engine
app.get('*', (req, res) => {
  res.render('index', { req });
});

// Start up the Node server
app.listen(PORT, () => {
  console.log(`Node server listening on http://localhost:${PORT}`);
});
開發者ID:FCPhoenix,項目名稱:project-frontend,代碼行數:30,代碼來源:server.ts

示例8: cacheControl

app.use(compression());

const accessLogStream = fs.createWriteStream(ROOT + '/morgan.log', {flags: 'a'})

app.use(morgan('common', {
  skip: (req, res) => res.statusCode < 400,
  stream: accessLogStream
}));

function cacheControl(req, res, next) {
  // instruct browser to revalidate in 60 seconds
  res.header('Cache-Control', 'max-age=60');
  next();
}
// Serve static files
app.use('/assets', cacheControl, express.static(path.join(__dirname, 'assets'), {maxAge: 30}));
app.use(cacheControl, express.static(path.join(ROOT, 'dist/client'), {index: false}));

//
/////////////////////////
// ** Example API
// Notice API should be in aseparate process

import { serverApi, createTodoApi } from './backend/api';
// Our API for demos only
app.get('/data.json', serverApi);
app.use('/api', createTodoApi());

process.on('uncaughtException', function (err) { 
  console.error('Catching uncaught errors to avoid process crash', err);
});
開發者ID:kuldeepkeshwar,項目名稱:universal-starter,代碼行數:31,代碼來源:server.aot.ts

示例9: require

const swaggerJSON = require('./swagger.json')

app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.use(methodOverride())

RegisterRoutes(app)
app.get(`/`, (req, res) => {
  res.redirect(`${basePath}swagger`)
})
app.use(`${basePath}healthz`, (_, res) => {
  res.send({
    status: 'Healthy!'
  })
})
app.use(`${basePath}swagger.json`, express.static(__dirname + './swagger.json'))
app.use(`${basePath}swagger`, swaggerUI.serve, swaggerUI.setup(swaggerJSON))

function startServer() {
  app.listen(process.env.PORT || 5002, () => {
    console.info(`App's running at http://localhost:${process.env.PORT || 5002}`)
    console.info('Press CTRL-C to stop\n')
  })
}

mongoose.connection.once('open', function() {
  console.info(`Connected to ${mongoDbUri}.`)
  app.emit('ready')
})

app.on('ready', function() {
開發者ID:Julianhm9612,項目名稱:coolstore-microservices,代碼行數:31,代碼來源:server.ts

示例10: recursive

    // Get all js files.
    recursive(SCRIPT_DIR, function (err, files) {
        files.forEach((filePath:string) => {
            if (filePath.indexOf(".map") < 0) {
                var path:string = filePath.substr(filePath.indexOf('js'));
                scriptList.push(
                    {
                        scriptPath: path
                    }
                );
            }
        });

        res.render("index.html", {
            scripts: scriptList
        });
    });
});

app.use(express.static(__dirname + "/../public/"));

// handle any 404 requests
var routes = app._router.stack.filter(router => {return router.route}).map(router => {return router.route.stack.map(stack => {return `${stack.method.toUpperCase()} \t${router.route.path}`}).join("\n")}).join("\n");
app.use(function(req, res){
    res.status(404).contentType("text/plain").send(`Could not ${req.method} ${req.path}\nTry:\n\n${routes}`)
});
app.listen(port, function(){
    console.log(`Listening to port:${port}`);
    console.log(`Routes:\n${routes}`);
});
開發者ID:bitDecayGames,項目名稱:DUArcade2016,代碼行數:30,代碼來源:app.ts


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