本文整理汇总了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(),
]
);
}
示例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
};
}
示例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))
示例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));
示例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));
示例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;
示例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);
示例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) => {
示例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);
}
示例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) => {