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


TypeScript koa-bodyparser.default方法代碼示例

本文整理匯總了TypeScript中koa-bodyparser.default方法的典型用法代碼示例。如果您正苦於以下問題:TypeScript koa-bodyparser.default方法的具體用法?TypeScript koa-bodyparser.default怎麽用?TypeScript koa-bodyparser.default使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在koa-bodyparser的用法示例。


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

示例1: middleware

export default function middleware(context: Koa) {
    const ctrlRouter = new WebApiRouter();
    return Compose(
        [
            asyncInit(),
            errorHandle(),
            KoaStatic(Path.join(__dirname, '../public'), { gzip: true }),
            Session({
                cookie: {
                    maxAge: SessionService.maxAge
                }
            }),
            sessionHandle(),
            Bodyparser({ jsonLimit: '50mb' }),
            ctrlRouter.router('../build/controllers', 'api'),
            routeFailed(),
        ]
    );
}
開發者ID:winken168,項目名稱:Hitchhiker,代碼行數:19,代碼來源:middleware.ts

示例2: function

export default function(swaggerDocument: any): Router {

  const router = new KoaRouter() as unknown as HttpRouter;
  const app = new Koa();

  // automatically convert legacy middleware to new middleware
  const appUse = app.use;
  app.use = (x) => appUse.call(app, koaConvert(x));

  let document: any;

  if (typeof swaggerDocument === 'string') {
    document = swagger.loadDocumentSync(swaggerDocument);
  } else {
    document = swaggerDocument;
  }

  if (!swagger.validateDocument(document)) {
    throw Error(`Document does not conform to the Swagger 2.0 schema`);
  }

  app.use(debug('swagger2-koa:router'));
  app.use(koaCors());
  app.use(body());
  app.use(validate(document));
  app.use(router.routes());
  app.use(router.allowedMethods());

  const full = (path: string) => document.basePath !== undefined ? document.basePath + path : path;

  return {
    get: (path, ...middleware) => router.get(full(path), ...middleware),
    head: (path, ...middleware) => router.head(full(path), ...middleware),
    put: (path, ...middleware) => router.put(full(path), ...middleware),
    post: (path, ...middleware) => router.post(full(path), ...middleware),
    del: (path, ...middleware) => router.del(full(path), ...middleware),
    patch: (path, ...middleware) => router.patch(full(path), ...middleware),
    app: () => app
  };
}
開發者ID:carlansley,項目名稱:swagger2-koa,代碼行數:40,代碼來源:router.ts

示例3: require

import * as bodyParser from 'koa-bodyparser';
const cors = require('@koa/cors');

import endpoints from './endpoints';

const handler = require('./api-handler').default;

// Init app
const app = new Koa();

app.use(cors({
	origin: '*'
}));

app.use(bodyParser({
	// リクエストが multipart/form-data でない限りはJSONだと見なす
	detectJSON: ctx => !ctx.is('multipart/form-data')
}));

// Init multer instance
const upload = multer({
	storage: multer.diskStorage({})
});

// Init router
const router = new Router();

/**
 * Register endpoint handlers
 */
endpoints.forEach(endpoint => endpoint.meta.requireFile
	? router.post(`/${endpoint.name}`, upload.single('file'), handler.bind(null, endpoint))
開發者ID:ha-dai,項目名稱:Misskey,代碼行數:32,代碼來源:index.ts

示例4: Koa

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

示例5: Koa

 }).then(async connection => {

    const app = new Koa();

    // Provides important security headers to make your app more secure
    app.use(helmet());

    // Logger middleware -> use winston as logger (logging.ts with config)
    app.use(logger(winston));

    app.use(bodyParser());

    // JWT middleware -> below this line routes are only reached if JWT token is valid, secret as env variable
    app.use(jwt({ secret: config.jwtSecret }));

    // this routes are protected by the JWT middleware, also include middleware to respond with "Method Not Allowed - 405".
    app.use(router.routes()).use(router.allowedMethods());

    app.listen(config.port);

    console.log(`Server running on port ${config.port}`);

}).catch(error => console.log('TypeORM connection error: ', error));
開發者ID:ryanwild,項目名稱:node-typescript-koa-rest,代碼行數:23,代碼來源:server.ts

示例6: Router

// e.g. https://www.npmjs.com/package/inversify-koa-utils)

// 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;
開發者ID:,項目名稱:,代碼行數:31,代碼來源:

示例7: Koa

import * as Koa from "koa";
import * as bodyParser from "koa-bodyparser";

const app = new Koa();

app.use(bodyParser({ strict: false }));

app.use((ctx) => {
    console.log(ctx.request.body);
    console.log(ctx.request.rawBody);
})

app.listen(80);
開發者ID:AbraaoAlves,項目名稱:DefinitelyTyped,代碼行數:13,代碼來源:koa-bodyparser-tests.ts

示例8: koa

import { api } from './defining_an_api';
import { createData } from './model_data';

const schema = api.getGraphQLSchema();

// Create Koa & Apollo GraphQL Server

const app = new koa();
const port = 3000;

const router = new koaRouter();
router.post('/graphql', graphqlKoa({ schema: schema }));
router.get('/graphql', graphqlKoa({ schema: schema }));
router.get('/graphiql', graphiqlKoa({ endpointURL: '/graphql' }));

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

app.listen(port);

console.log(`GraphQL Server is running on port ${port}.`);
console.log(`GraphiQL UI is running at http://localhost:${port}/graphiql`);

// Load sample data

createData()
.then(() => {
    console.log('Data Loaded.');
})
.catch((e) => {
開發者ID:RevFramework,項目名稱:rev-framework,代碼行數:31,代碼來源:serving_an_api.ts

示例9: getPm2File

});

router.post('/setup/env', (ctx, next) => {
    const pm2Obj = getPm2Obj();
    pm2Obj.apps[0].env = ctx.request.body;
    pm2Obj.apps[0].script = 'index.js';
    fs.writeFileSync(getPm2File(), JSON.stringify(pm2Obj), 'utf8');
    try {
        execSync('pm2 -V', { encoding: 'utf8' });
    } catch (e) {
        execSync(`npm install pm2 -g`);
    }
    const stdout = execSync(`pm2 start ${getPm2File()}`, { encoding: 'utf8' });
    ctx.body = stdout;
});

app.use(KoaStatic(path.join(__dirname, 'public'), { gzip: true }))
    .use(Bodyparser())
    .use(router.routes())
    .use(router.allowedMethods());

app.listen(9527);

function getPm2File() {
    return path.join(__dirname, 'pm2.json');
}

function getPm2Obj() {
    const pm2Content = fs.readFileSync(getPm2File(), 'utf8');
    return JSON.parse(pm2Content);
}
開發者ID:winken168,項目名稱:Hitchhiker,代碼行數:31,代碼來源:setup.ts

示例10: next

import * as jwt from 'jsonwebtoken';
import * as mount from 'koa-mount';
import * as responseTime from 'koa-response-time';
import { UserService } from './routes/users/user.service';
import { BindRoutes } from './routes';

const APP_CONFIG = config.get('app');
const JWT_CONFIG = config.get('jwt');
const app = new Koa();
const userService = new UserService();

// X-Response-Time
app.use(responseTime());

// Body Parsing
app.use(bodyparser());

// 404 Handler
app.use(async (ctx, next) => {
  await next();
  if (ctx.status === 404) {
    ctx.response.status = 404;
    ctx.response.body = {
      error: true,
      message: 'Entity not found'
    };
  }
});

// 401 Handler
app.use(async (ctx, next) => {
開發者ID:HackrLabs,項目名稱:HakrPass,代碼行數:31,代碼來源:server.ts


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