本文整理匯總了TypeScript中serve-favicon.default方法的典型用法代碼示例。如果您正苦於以下問題:TypeScript serve-favicon.default方法的具體用法?TypeScript serve-favicon.default怎麽用?TypeScript serve-favicon.default使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類serve-favicon
的用法示例。
在下文中一共展示了serve-favicon.default方法的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。
示例1: function
export default function(app) {
let env = app.get('env');
app.set('views', config.root + '/server/views');
app.set('view engine', 'jade');
app.use(compression());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(cookieParser());
app.use(passport.initialize());
app.set('appPath', path.join(config.root, 'client'));
if ('production' === env) {
app.use(favicon(path.join(config.root, 'client', 'favicon.ico')));
app.use(express.static(app.get('appPath')));
app.use(morgan('dev'));
}
if ('development' === env) {
app.use(require('connect-livereload')());
}
if ('development' === env || 'test' === env) {
app.use(express.static(path.join(config.root, '.tmp')));
app.use(express.static(app.get('appPath')));
app.use(morgan('dev'));
app.use(errorHandler()); // Error handler - has to be last
}
}
示例2: listen
/**
* Begin listening for connections, also finalizes many configuration options
*
* @param {number} port (Optional) The port to listen on for connections
* @param {string} host (Optional) The host address to listen on, if left blank will use 0.0.0.0
* @return {ExpressMvc}
*/
listen(port?: number, host?: string): ExpressMvc {
port = port || 3000;
// Busboy Setup
extend(this.express, this.defaults.busboy);
if (this.defaults.busboy.allowUpload) {
console.log(`Files will be uploaded to ${this.defaults.busboy.uploadPath}.`);
} else {
console.log('File uploads are not permitted.');
}
// Setup Viewengine
this.express.set('views', this.defaults.views.path);
this.express.set('view engine', this.defaults.views.engine);
if (this.defaults.views.engineImpl) {
this.express.engine(this.defaults.views.engine, this.defaults.views.engineImpl);
}
// Favicon Setup
if (this.defaults.favicon.path) {
this.express.use(favicon(this.defaults.favicon.path));
}
// Static Files setup
this.defaults.staticFiles.paths.forEach(path => {
this.express.use(e.static(path));
});
let routes = this.routerBuilder.build();
for (let route of routes) {
if (!route.path) continue;
let middleware = this.routerBuilder.sortMiddleware(route.middleware);
route.router.use(...middleware);
this.express.use(route.path, route.router);
}
this.httpServer.listen(port, () => {
console.log(`Listening on port ${port}...`);
this.running = true;
});
return this;
}
示例3: createServer
export default function createServer(
{ base, port, host, title }: Server,
{ key, cert }: SSLBuffer
): SocketIO.Server {
const basePath = trim(base);
events.emit(
'debug',
`key: ${key}, cert: ${cert}, port: ${port}, base: ${base}, title: ${title}`
);
const html = (
req: express.Request,
res: express.Response
): express.Response =>
res.send(`<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<title>${title}</title>
<link rel="stylesheet" href="${basePath}/public/index.css" />
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous">
</head>
<body>
<div id="overlay">
<div class="error">
<div id="msg"></div>
<input type="button" onclick="location.reload();" value="reconnect" />
</div>
</div>
<div id="options">
<a class="toggler"
href="#"
alt="Toggle options"><i class="fas fa-cogs"></i></a>
<textarea class="editor"></textarea>
</div>
<div id="terminal"></div>
<script src="${basePath}/public/index.js"></script>
</body>
</html>`);
const app = express();
app
.use(morgan('combined', { stream: logger.stream }))
.use(helmet())
.use(compression())
.use(favicon(path.join(distDir, 'favicon.ico')))
.use(`${basePath}/public`, express.static(distDir))
.use((req, res, next) => {
if (
req.url.substr(-1) === '/' &&
req.url.length > 1 &&
!/\?[^]*\//.test(req.url)
)
res.redirect(301, req.url.slice(0, -1));
else next();
})
.get(basePath, html)
.get(`${basePath}/ssh/:user`, html);
return socket(
!isUndefined(key) && !isUndefined(cert)
? https.createServer({ key, cert }, app).listen(port, host, () => {
events.server(port, 'https');
})
: http.createServer(app).listen(port, host, () => {
events.server(port, 'http');
}),
{ path: `${basePath}/socket.io` }
);
}
示例4: config
config(): void {
let server: http.Server,
db: DB,
api: API,
serverPort = AppConfig.serverPort;
debug("toby:server");
this.app.use(logger("dev"));
this.app.use(bodyParser.json());
this.app.use(bodyParser.urlencoded({ extended: false }));
this.app.use(cookieParser());
this.app.set("view engine", "hbs");
this.app.set("views", path.join(__dirname, "../views"));
this.app.use(
favicon(path.join(__dirname, "../public", "images", "toby.ico"))
);
this.app.use(express.static(path.join(__dirname, "../public")));
this.app.set("port", serverPort);
server = http.createServer(this.app);
server.listen(serverPort);
server.on("error", (error: NodeJS.ErrnoException) => {
if (error.syscall !== "listen") {
throw error;
}
const bind =
typeof serverPort === "string"
? `Pipe ${serverPort}`
: `Port ${serverPort}`;
// handle specific listen errors with friendly messages
switch (error.code) {
case "EACCES":
console.error(bind + " requires elevated privileges");
process.exit(1);
break;
case "EADDRINUSE":
console.error(bind + " is already in use");
process.exit(1);
break;
default:
throw error;
}
});
server.on("listening", () => {
const addr = server.address();
const bind =
typeof addr === "string" ? `pipe ${addr}` : `port ${addr.port}`;
debug(`Listening on ${bind}`);
console.log(`Listening on ${bind}`);
});
db = new DB();
api = new API(db, server);
this.app.get("/", (_req, res, _next) => {
res.render("index", { title: pkgJSON.title });
});
this.app.use("/api", api.router);
// catch 404 and forward to error handler
this.app.use((req, _res, next) => {
let err = new Error("Not Found");
err["status"] = 404;
console.log(req.path);
next(err);
});
// development error handler
// will print stacktrace
if (this.app.get("env") === "development") {
this.app.use(
(
err: Error,
_req: express.Request,
res: express.Response,
_next: express.NextFunction
) => {
res.status(err["status"] || 500);
console.log(err.stack);
res.render("error", {
message: err.message,
error: err
});
}
);
}
// production error handler
// no stacktraces leaked to user
this.app.use(
(
err: Error,
_req: express.Request,
//.........這裏部分代碼省略.........
示例5: configureMiddleware
//<% } %>
/**
* Configuring app-level Middleware
*/
configureMiddleware() {
// Instructs Express to serve your favicon
this.app.use( favicon( path.join( __dirname, 'Assets/Images', 'favicon.ico' ) ) );
// Setting logging middleware
this.app.use( logger( 'dev' ) );
/*app.use(session({
cookie: {
path: '/back'
//domain: ''
},
resave: false,
saveUninitialized: false,
secret: 'winter is coming',
store: store,
unset: 'destroy'
}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());*/
// Setting up all possible folders for serving static files ( JS, CSS, Fonts, Images )
this.app.use( express.static( path.join( __dirname, this.viewsFolder ) ) );
this.app.use( express.static( path.join( __dirname, 'Config' ) ) );
this.app.use( express.static( path.join( __dirname, 'Assets' ) ) );
this.app.use( express.static( path.join( __dirname, 'Models' ) ) );
this.app.use( express.static( path.join( __dirname, 'node_modules' ) ) );
}
示例6: if
export let parserInit = ()=> {
app.use(favicon(path.resolve('favicon.ico')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
if (SERVER_CONFIG.env === DEV) {
app.use(logger(DEV));
var whitelist = ['http://127.0.0.1:3008','http://127.0.0.1:3006'];
var corsOptionsDelegate = function(req, callback){
var corsOptions;
if(whitelist.indexOf(req.header('Origin')) !== -1){
corsOptions = { origin: true ,credentials:true}; // reflect (enable) the requested origin in the CORS response
}else{
corsOptions = { origin: false }; // disable CORS for this request
}
callback(null, corsOptions); // callback expects two parameters: error and options
};
/*var corsOptions = {
origin: 'http://127.0.0.1:3008',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
};*/
app.use(cors(corsOptionsDelegate));//white List
//app.options('http://127.0.0.1:3008', cors());//If allowed Access-Control-Allow-Originďź* Be sure to write
}
else if (SERVER_CONFIG.env === PROD) {
app.use(logger('prod'));
}
timeoutParser.init();
errParser.init();
parserInit = ()=> {
throw new Error("parsers/index.ts: parsers have been initialized.");
}
}
示例7: serve
export const StaticRoutes = (app: Express.Application) => {
app.use('/sw.js', serve('../client/sw.js'));
app.use('/', serve('../static'));
app.use('/i18n', serve('../../i18n'));
app.use('/client', serve('../client'));
app.use(favicon(path.resolve(__dirname, '../static/logo.png')));
app.post('/log/error', (req: Request, res: Response) => {
const err: any = req.body.error;
Logger.error('error during rendering: %s; error: %s', req.url, JSON.stringify(err, Object.getOwnPropertyNames(err)));
res.status(200).json({});
});
};
示例8: configureApp
configureApp() {
let host = nconf.get("HostInfo");
let corsOptions = {
origin: host.SPAUrl,
methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
credentials: true,
preflightContinue: false
};
// uncomment after placing your favicon in /public
this.app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
this.app.use(cors(corsOptions));
this.app.use(logger('dev'));
this.app.use(bodyParser.json());
this.app.use(bodyParser.urlencoded({ extended: false }));
this.app.use(cookieParser());
this.app.use(session({ secret: 'hakans planner hackathon', resave: false, saveUninitialized: false }));
this.app.use(express.static(path.join(__dirname, 'public')));
// setup view engine
this.app.set('views', path.join(__dirname, 'views'));
this.app.set('view engine', 'jade');
}
示例9: loadRoutes
export function loadRoutes(app: express.Express): void {
if (getNodeEnv() === 'development') {
app.use(logger('dev'));
require('./livereload')(app);
}
app.use(favicon(config.root + '/public/assets/img/favicon.ico'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(compress());
app.use(express.static(config.root + '/public'));
app.use(methodOverride());
app.use((req, res) => {
res.status(404).sendFile(`${config.root}/public/404.html`);
});
app.use((err: any, req: any, res: any, next: any) => {
console.log(err);
res.status(500).sendFile(`${config.root}/public/500.html`);
});
};
示例10: express
import * as express from 'express'
import * as helmet from 'helmet'
import * as path from 'path'
import * as favicon from 'serve-favicon'
const app = express()
app.use(helmet())
// dotenv is loaded by foreman
import { MediaType, mediaTypes } from './config'
import fetchMethods from './services/airtable'
import fetchDetailMethods from './services/tmdb'
app.use('/static', express.static(path.join(__dirname, '../../public')))
app.use(favicon(path.join(__dirname, '../../public/favicon.ico')))
mediaTypes.map((mt: MediaType) => {
// lists of ids
app.get(`/api/${mt}`, async (req, res) => {
res.json(await fetchMethods[mt]())
})
// tmdb calls, but not for books
if (mt !== 'books') {
app.get(`/api/${mt}/:id`, async (req, res) => {
res.json(await fetchDetailMethods[mt](req.params.id))
})
}
})