当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript koa-router.routes函数代码示例

本文整理汇总了TypeScript中koa-router.routes函数的典型用法代码示例。如果您正苦于以下问题:TypeScript routes函数的具体用法?TypeScript routes怎么用?TypeScript routes使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了routes函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。

示例1: constructor

    /**
     * Constructor
     * @param application: the KOA application
     */
    constructor (webServer: WebServer) {
        this.webServer = webServer;
        this.router = new KoaRouter();

        // Create routes
        this.openDevTools();
        this.getVersion();
        this.getOsPlatform();
        this.getAddress();

        this.getOpenedFile();
        this.setOpenedFile();
        
        webServer.localApplication.use(this.router.routes());
        webServer.externApplication.use(this.router.routes());
    }
开发者ID:BabylonJS,项目名称:Editor,代码行数:20,代码来源:tools.ts

示例2: createHttpServer

export function createHttpServer(): HttpServer {
  const koa = new Koa()
  installMiddlewares(koa)
  const router = new KoaRouter()
  koa.use(router.routes())
  koa.use(router.allowedMethods())
  return httpCreateServer(koa.callback())
}
开发者ID:ohjames,项目名称:blaggart,代码行数:8,代码来源:index.ts

示例3: async

const main = async () => {
    const app = new Koa();
    const router = new Router();
    const apolloServer = new ApolloServer({
        formatError: err => {
            logger.error(err);
            return err;
        },
        schema: Schema,
        playground: {
            endpoint: "/tictactoe/graphql"
        }
    });
    apolloServer.applyMiddleware({ app });

    app.use(koabody());

    router.get("/ping", async ctx => {
        ctx.body = "pong";
    });

    app.use(router.routes());

    app.use(koaBunyanLogger());
    app.use(koaBunyanLogger.requestLogger());

    process.on("unhandledRejection", err => {
        logger.error(err);
    });

    await connectWithRetry();
    const server = createServer(app.callback());

    SubscriptionServer.create(
        {
            schema: Schema,
            execute,
            subscribe
        },
        {
            server,
            path: "/ws"
        }
    );

    server.listen(3000, () => {
        logger.info("listening on 3000");
    });
};
开发者ID:mattcroberts,项目名称:tic-tac-toe,代码行数:49,代码来源:main.ts

示例4: Koa

app.prepare().then(() => {
  const server = new Koa();
  const router = new Router();

  router.get('*', async ctx => {
    await handle(ctx.req, ctx.res);
    ctx.respond = false;
  });

  server.use(async (ctx, next) => {
    ctx.res.statusCode = 200;
    await next();
  });

  server.use(router.routes());

  server.listen(port);
});
开发者ID:Ushinji,项目名称:next_sample,代码行数:18,代码来源:server.ts

示例5: setRouters

export function setRouters(app: Koa, RouterClass: any[]): void {
  RouterClass.forEach(Router => {
    return new Router()
  })

  routerSet.forEach(Func => {
    Func()
  })

  app.use(koaRouter.routes())

  app.use(async (ctx) => {
    ctx.res.setHeader('Access-Control-Allow-Origin', ctx.request.header.origin || '*')
    ctx.res.setHeader('Access-Control-Allow-Credentials', 'true')
    ctx.res.setHeader('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS')
    ctx.res.setHeader('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With, AUTHORIZATION, X-Socket-Id')
  })
}
开发者ID:Brooooooklyn,项目名称:teambition-auth,代码行数:18,代码来源:router.ts

示例6: createConnection

createConnection().then(async connection => {

    // create koa app
    const app = new Koa();
    const router = new Router();

    // register all application routes
    AppRoutes.forEach(route => router[route.method](route.path, route.action));

    // run app
    app.use(bodyParser());
    app.use(router.routes());
    app.use(router.allowedMethods());
    app.listen(3000);

    console.log("Koa application is up and running on port 3000");

}).catch(error => console.log("TypeORM connection error: ", error));
开发者ID:willchapin,项目名称:typescript-koa-example,代码行数:18,代码来源:index.ts

示例7: default

export default (app?: Koa) => {
  const provided = !!app

  const middlewares = [bodyParser(), router.routes(), router.allowedMethods()]

  if (!app) {
    app = new Koa()
    app.keys = app.keys = (process.env.APP_KEYS || '').split(',')
    middlewares.unshift(session({}, app))
  }

  if (provided) {
    return middlewares
  }

  app.use(compose(middlewares))

  app.listen(serverPort + 1, serverHost, () => {
    debug('Router server is now running at %s:%s', serverHost, serverPort + 1)
  })
}
开发者ID:JounQin,项目名称:blog,代码行数:21,代码来源:index.ts

示例8: webpackServeWaitpage

    add: (app, middleware, options) => {
      app.use(
        webpackServeWaitpage(options, {
          template: fs.readFileSync(
            path.join(config.paths.gitRoot, 'webpack', 'config', 'waitpage.ejs'),
            'utf8'
          )
        })
      )

      app.use(mount('/node_modules', serve(config.paths.nodeModules)))

      app.use(
        mount('/currencies', serve(path.join(config.paths.vendor, 'game-currency-formats', 'src')))
      )

      // Make sure the usage of webpack-serve-waitpage will be before the following commands if exists
      middleware.webpack()
      middleware.content()

      app.use(router.routes())
    }
开发者ID:borestad,项目名称:playground,代码行数:22,代码来源:config.webpack.serve.ts

示例9: createServer

function createServer() {
  const app = new Koa();
  app.use(bodyParser());
  app.use(cors());
  app.use(staticFiles(path.join(__dirname, 'public')));

  const router = new Router();
  router.get('/api/animals', async (ctx) => {
    ctx.body =  [
      {id: 1, name: 'cat'},
      {id: 2, name: 'dog'},
      {id: 3, name: 'fish'}
    ];
  });

  app.use(async (ctx, next) => {
    try {
      await next();
    } catch (err) {

      const error = {
        errorType: 'UNHANDLED_ERROR',
        message: err.message,
        stack: err.stack
      };

      ctx.body = error;
      // tslint:disable-next-line:no-console
      console.error(error);
    }
  });

  app
  .use(router.routes())
  .use(router.allowedMethods());

  return app;
}
开发者ID:stevejhiggs,项目名称:macgyver,代码行数:38,代码来源:server.ts

示例10: Date

});


// logger

app.use(function *(next){
  const start = new Date().getTime();
  yield next;
  const ms = new Date().getTime() - start;
  console.log('%s %s - %s', this.method, this.url, ms);
});

// Redirect

redirect_router.redirect('/', '/static/main.html');
app.use(redirect_router.routes());
app.use(redirect_router.allowedMethods());

// static

app.use(mount('/static', serve('../frontend/build')));


// responses under /api

router.get('/hello', function *(next) {
  this.body = 'hello';
});


function query_to_linestring(points) {
开发者ID:cyounkins,项目名称:uber-homework,代码行数:31,代码来源:main.ts

示例11: require

/// <reference path="./d.ts/node.d.ts" />
/// <reference path="./d.ts/koa.d.ts" />

import {YabpConfig} from './modules/config/config.ts';

import databaseSetup = require('./modules/db/databaseSetup.ts')
import koa = require('koa');

var router = require('koa-router');
var yabpServer = new koa();

router
  .get("/REST/config/isConfigured", function* (next){
    this.statusCode = 200;
    this.set('Access-Control-Allow-Origin','http://localhost:9000')
    this.body = { isConfigured : false };
  })

yabpServer.use(router.routes()).use(router.allowedMethods());
yabpServer.listen(1988);
开发者ID:Paincraft,项目名称:yabp,代码行数:20,代码来源:yabp.ts

示例12: Router

import { ensureAuthenticated } from './authUtils';
import * as Router from 'koa-router';
import * as authController from './auth.controller';
import * as meController from './me.controller';
import * as github from './github';
import * as google from './google';
import * as facebook from './facebook';
import * as linkedin from './linkedin';
import * as live from './live';
import * as twitter from './twitter';

const router = new Router();

// routes
router.post('/login', authController.login);
router.post('/signup', authController.signup);
router.post('/github', github.authenticate);
router.post('/google', google.authenticate);
router.post('/facebook', facebook.authenticate);
router.post('/linkedin', linkedin.authenticate);
router.post('/live', live.authenticate);
router.post('/twitter', twitter.authenticate);

// auth only applied for following routes, not the routes above
router.use(['/me', '/unlink'], ensureAuthenticated);
router.get('/me', meController.getMe );
router.put('/me', meController.updateMe );
router.get('/unlink/:provider', meController.unlink);

export default router.routes();
开发者ID:ghiscoding,项目名称:Realtime-TODO-Aurelia-RethinkDB,代码行数:30,代码来源:index.ts

示例13: saveVisitList

    // record visit
    if (whiteList[ctx.request.ip] === undefined) {
      visitList[ctx.request.ip] = Date.now();
      saveVisitList();
    }

    ctx.response.status = 200;
    ctx.body = JSON.stringify({
      statistics: { ...flavor },
      code: 200
    });
  } catch (e) {
    ctx.response.status = 400;
    ctx.body = JSON.stringify(
      {
        message: e.message,
        code: 400
      },
      null,
      2
    );
  } finally {
    fs.writeFileSync("./config.json", JSON.stringify(flavor, null, 2), "utf-8");
  }
});

loadConfig();
app.use(Koabody());
app.use(router.routes()).listen(8080);
开发者ID:TeamCovertDragon,项目名称:duanwu-statistics,代码行数:29,代码来源:index.ts

示例14: next

  .post('/:url/unpublish', blogController.unpublish);

api.use(async (ctx, next) => {
  let auth = ctx.headers.auth;

  if (auth == Keys.api[ctx.method]) {
    await next();
  } else {
    ctx.status = 401;
    ctx.body = 'Unauthorized';
  }
})

api.get('/counts', countController.list)
  .post('/images', upload.single('file'), imageController.create)
  .use('/games', game.routes(), game.allowedMethods())
  .use('/gourmets', gourmet.routes(), gourmet.allowedMethods())
  .use('/hearthstone-seasons', hearthstoneSeason.routes(), hearthstoneSeason.allowedMethods())
  .use('/hearthstone-decks', hearthstoneDeck.routes(), hearthstoneDeck.allowedMethods())
  .use('/hearthstone-matches', hearthstoneMatch.routes(), hearthstoneMatch.allowedMethods())
  .get('/hearthstone-cards', hearthstoneCardController.list)
  .post('/game-trophy', trophyController.scrap)
  .use('/blogs', blog.routes(), blog.allowedMethods());

router.use('/api', api.routes(), api.allowedMethods())
  .get('/admin*', auth({ name: Keys.admin.user, pass: Keys.admin.password }), async (ctx, next) => {
    await send(ctx, 'admin.html', { root: path.join(__dirname, '..', '/public') });
  })
  .get('*', async (ctx, next) => {
    await send(ctx, 'index.html', { root: path.join(__dirname, '..', '/public') });
  })
开发者ID:Bill0106,项目名称:MySite,代码行数:31,代码来源:routes.ts

示例15: Router

// Read more about routing at https://github.com/alexmingoia/koa-router
const router = new Router({prefix: '/api'});
router.get('/people', getAllPeople);
router.get('/todos', getAllTodo);
router.get('/todos/:id', getTodo);
router.post('/todos', addTodo);
router.patch('/todos/:id', patchTodo);
router.delete('/todos/:id', deleteTodo);

// Read more about koa at http://koajs.com/
const app = new Koa();
app.use(cors());
app.use(logger());
app.use(bodyParser());
app.use(router.routes());

// Read more about koa views at https://github.com/queckezz/koa-views
// Read more about Nunjucks at https://mozilla.github.io/nunjucks/
const viewPath = path.join(__dirname, 'views');
app.use(views(viewPath, {
  map: {html: 'nunjucks'},
  options: {loader: new FileSystemLoader(viewPath)}
}));
app.use(async (ctx, next) => {
  // If nothing else was found, render index (assumption: single-page app)
  await ctx.render('index');
});

const port: (number|string) = process.env.PORT || 8080;
app.listen(port, () => {
开发者ID:,项目名称:,代码行数:30,代码来源:


注:本文中的koa-router.routes函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。