koa-router.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. /*!
  2. * koa-better-body <https://github.com/tunnckoCore/koa-better-body>
  3. *
  4. * Copyright (c) 2014 Charlike Mike Reagent, Daryl Lau, contributors.
  5. * Released under the MIT license.
  6. */
  7. 'use strict';
  8. /*!
  9. * Module dependencies.
  10. */
  11. var log = console.log,
  12. app = require('koa')(),
  13. router = require('koa-router'),
  14. koaBody = require('../index'),
  15. multiline = require('multiline'),
  16. port = process.env.PORT || 4291,
  17. host = process.env.HOST || 'http://localhost';
  18. app.use(router(app));
  19. /*!
  20. * Accepts only urlencoded and json bodies.
  21. */
  22. app.post('/post/users', koaBody(),
  23. function *(next) {
  24. log(this.request.body);
  25. // => POST body object
  26. this.body = JSON.stringify(this.request.body, null, 2);
  27. yield next;
  28. }
  29. );
  30. /*!
  31. * Display HTML page with basic form.
  32. */
  33. app.get('/', function *(next) {
  34. this.set('Content-Type', 'text/html');
  35. this.body = multiline.stripIndent(function(){/*
  36. <!doctype html>
  37. <html>
  38. <body>
  39. <form action="/post/upload" enctype="multipart/form-data" method="post">
  40. <input type="text" name="username" placeholder="username"><br>
  41. <input type="text" name="title" placeholder="title of file"><br>
  42. <input type="file" name="uploads" multiple="multiple"><br>
  43. <button type="submit">Upload</button>
  44. </body>
  45. </html>
  46. */});
  47. yield next;
  48. });
  49. /*!
  50. * Accepts `multipart`, `json` and `urlencoded` bodies.
  51. */
  52. app.post('/post/upload',
  53. koaBody({
  54. multipart: true,
  55. formidable: {
  56. uploadDir: __dirname + '/uploads'
  57. }
  58. }),
  59. function *(next) {
  60. log(this.request.body.fields);
  61. // => {username: ""} - if empty
  62. log(this.request.body.files);
  63. /* => {uploads: [
  64. {
  65. "size": 748831,
  66. "path": "/tmp/f7777b4269bf6e64518f96248537c0ab.png",
  67. "name": "some-image.png",
  68. "type": "image/png",
  69. "mtime": "2014-06-17T11:08:52.816Z"
  70. },
  71. {
  72. "size": 379749,
  73. "path": "/tmp/83b8cf0524529482d2f8b5d0852f49bf.jpeg",
  74. "name": "nodejs_rulz.jpeg",
  75. "type": "image/jpeg",
  76. "mtime": "2014-06-17T11:08:52.830Z"
  77. }
  78. ]}
  79. */
  80. this.body = JSON.stringify(this.request.body, null, 2);
  81. yield next;
  82. }
  83. );
  84. app.listen(port);
  85. log('Visit %s:%s/ in browser.', host, port);
  86. log();
  87. log('Test with executing this commands:');
  88. log('curl -i %s:%s/post/users -d "user=admin"', host, port);
  89. log('curl -i %s:%s/post/upload -F "source=@%s/avatar.png"', host, port, __dirname);
  90. log();
  91. log('Press CTRL+C to stop...');