How to use koa-bodyparser - 10 common examples

To help you get started, we’ve selected a few koa-bodyparser examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github BUPT-HJM / vue-blog / server / middleware / index.js View on Github external
export default function middleware() {
    return convert.compose(
        logger(),
        bodyParser(),
        compress({
            filter: function (content_type) {
                if (/event-stream/i.test(content_type)) {
                    // 为了让hot reload生效,不对__webpack_hmr压缩
                    return false;
                } else {
                    return true;
                }
            },
        })
    );
}
github yixianle / google-translate / app / index.js View on Github external
import config from '../config/config';
import router from './routes';
import middlewares from './middlewares';


const app = new Koa();

// console.log(config.secretKeyBase, '-------config.secretKeyBase------')
app.keys = [config.secretKeyBase];

app.use(convert(require('koa-static')(path.join(__dirname + '/../public'))));



app.use(bodyParser());
app.use(methodOverride((req, _res) => {
  if (req.body && (typeof req.body === 'object') && ('_method' in req.body)) {
    // look in urlencoded POST bodies and delete it
    const method = req.body._method;
    delete req.body._method;
    return method;
  }
}));
app.use(convert(json()));
app.use(convert(logger()));

//views with pug
app.use(views(__dirname + '/views', { extension: 'pug' }));

// catch error
// 临时注释
github storyforj / fervor / src / server / server.js View on Github external
export default async function startApp(options = {}) {
  const app = new Koa();

  app.use(requestLogger(logger));
  app.use(handleErrors(options));

  const pgqlOpts = setPGQLOpts(options);
  const pgPool = createPgPool(options, pgqlOpts);
  await startSchemaWatcher(pgPool, 'public', pgqlOpts);
  app.use(postgraphile(pgPool, 'public', pgqlOpts));

  app.use(cors());
  app.use(bodyParser());
  app.use(cookie());

  // load any user defined middleware
  const middleware = load('middleware', { options, default: () => {} });
  if (middleware.default) {
    middleware.default({ app, logger, options });
  }

  app.use(appManifest(options));
  if (!options.disableWebpack) {
    // eslint-disable-next-line global-require
    await require('../config/webpack.dev').default(app, options);
  }
  app.use(staticAssets(options));
  app.use(ssr(options));
github pranavpr / koa2-es2017-api-boilerplate / src / app.js View on Github external
import Koa from 'koa';
import cors from '@koa/cors';
import logger from 'koa-morgan';
import bodyParser from 'koa-bodyparser';
import router from './routes';

const app = new Koa();

// Set middlewares
app.use(
  bodyParser({
    enableTypes: ['json', 'form'],
    formLimit: '10mb',
    jsonLimit: '10mb'
  })
);

// Logger
app.use(
  logger('dev', {
    skip: () => app.env === 'test'
  })
);

// Enable CORS
app.use(cors());
github chentsulin / koa-context-validator / src / __tests__ / index.spec.js View on Github external
it('body', async () => {
    const app = new Koa();

    let error;
    app.use(async (ctx, next) => {
      try {
        await next();
      } catch (err) {
        error = err;
      }
    });
    app.use(bodyParser());
    app.use(validator({
      body: object().keys({
        username: string().required(),
      }),
    }));

    await request(app.listen())
      .post('/');

    expect(error.name).to.equal('ValidationError');
    expect(error.message).to.equal('child "username" fails because ["username" is required]');
  });
github yrong / koa-neo4j / src / index.js View on Github external
this.neo4jConnection = new Neo4jConnection(options.neo4j);
        this.neo4jInitialized = this.neo4jConnection.initialized;

        const server = http.createServer(this.callback());
        this.server = server;

        if (!options.loadMiddlewareByApp) {
            this.configuredAuthentication = false;
            if (options.authentication)
                this.configureAuthentication(options.authentication);


            this
                .use(cors(options.cors))
                .use(bodyParser({
                    onerror(error, ctx) {
                        ctx.throw(400, `cannot parse request body, ${JSON.stringify(error)}`);
                    }
                }));

            this.use(async (ctx, next) => {
                try {
                    const start = new Date();
                    await next();
                    const ms = new Date() - start;
                    console.log('%s %s - %s ms', ctx.method, ctx.originalUrl, ms);
                } catch (error) {
                    ctx.body = String(error);
                    ctx.status = error.status || 500;
                    console.log('%s %s - then%s', ctx.method, ctx.originalUrl,
                        error.stack || error);
github qious / gallery-server / src / app.ts View on Github external
import Koa from 'koa'
import koaBody from 'koa-bodyparser'
import config from 'config'

import router from './middleware/router'
import session from './middleware/session'

const app = new Koa()

app.keys = config.get('keys')

app.use(koaBody())

app.use(session())

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

export default app
github interledgerjs / rafiki / packages / rafiki-admin-api / src / index.ts View on Github external
private _getRoutes (
    peers: PeersService,
    accounts: AccountsService
  ): createRouter.Router {
    const middlewareRouter = createRouter()

    middlewareRouter.use(bodyParser())
    middlewareRouter.route({
      method: 'get',
      path: '/health',
      handler: async (ctx: Context) => {
        ctx.body = 'Status: ok'
      }
    })
    middlewareRouter.route({
      method: 'get',
      path: '/stats',
      handler: async (ctx: Context) => ctx.assert(false, 500, 'not implemented')
    })
    middlewareRouter.route({
      method: 'get',
      path: '/alerts',
      handler: async (ctx: Context) => ctx.assert(false, 500, 'not implemented')
github ddellamico / koa-rest-api-es6 / src / middleware / index.js View on Github external
export default function () {
  return compose([
    helmet(),
    convert(cors()),
    convert(bodyParser()),
    convert(methodOverride()),
    handleError()
  ]);
}
github codevet / daipay / src / server / server.js View on Github external
import fs from 'fs'
import path from 'path'
import Koa from 'koa'
import koaLogger from 'koa-logger'
import Router from 'koa-router'
import bodyParser from 'koa-bodyparser'
import mount from 'koa-mount'
import api from './api_v1'

const router = new Router()
const app = new Koa()

if (__DEV__ || __TEST__)
  app.use(koaLogger())
app
  .use(bodyParser())
  .use(router.routes())
  .use(mount('/api/v1',api.routes()))

if (__DEV__) {
  const requireFunc = typeof __webpack_require__ === "function" ? __non_webpack_require__ : require;
  const koaWebpack = require('koa-webpack')
  const serve = require('koa-static')
  const [webConfig, ] = requireFunc('../tools/app.webpack.config.js')()
  koaWebpack({
    config: webConfig,
    devMiddleware: {index:false}
  }).then(middleware => {
    app.use(middleware)
    app.use(serve('./static')) 
    app.use(async (ctx, next) => {
      if (ctx.request.method === 'POST') {

koa-bodyparser

a body parser for Koa

MIT
Latest version published 10 months ago

Package Health Score

86 / 100
Full package analysis

Popular koa-bodyparser functions