Last active
April 29, 2018 17:08
-
-
Save constgen/f1f640c8421befa596c2f58ad3d839d4 to your computer and use it in GitHub Desktop.
Koa2 with router and Hot Module Replacement
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 'use strict'; | |
| let Koa = require('koa'); | |
| let jsonBody = require('koa-json-body'); | |
| let router = require('./router'); | |
| let defaultErrorHandler = require('./default-error-handler'); | |
| module.exports = new Koa() | |
| .use(defaultErrorHandler) | |
| .use(jsonBody({ limit: '1mb', fallback: true, strict: true })) | |
| .use(router.routes()) | |
| .use(router.allowedMethods()) | |
| .on('error', function (err, ctx) { | |
| console.error(err, ctx); | |
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 'use strict'; | |
| module.exports = function (ctx, next) { | |
| return next().catch(function (err) { | |
| ctx.status = err.statusCode || err.status || 500; | |
| ctx.body = err.message; | |
| }); | |
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 'use strict'; | |
| let http = require('http'); | |
| const PORT = process.env.PORT || 8080; | |
| let currentApp = require('./app').callback(); | |
| let server = http.createServer(currentApp).listen(PORT, function () { | |
| console.log(`Server started on: http://localhost:${PORT}`); | |
| }); | |
| if (module.hot) { | |
| module.hot.accept('./app', function () { | |
| try { | |
| server.removeListener('request', currentApp); | |
| currentApp = require('./app').callback(); | |
| server.on('request', currentApp); | |
| } catch (err) { | |
| console.error(err); | |
| } | |
| }); | |
| module.hot.accept(); | |
| module.hot.dispose(function () { | |
| console.log('Server stopped'); | |
| server.close(); | |
| }); | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 'use strict'; | |
| var Router = require('koa-router'); | |
| var router = new Router(); | |
| module.exports = router | |
| .get('/', function ({ request, response }) { | |
| response.body = ''; | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment