var koa = require('koa'); var router = require('koa-router'); var app = koa(); var _ = router(); _.get('/not_found', printErrorMessage); _.get('/hello', printHelloMessage); app.use(_.routes()); app.use(handle404Errors); function *printErrorMessage(){ this.status = 404; this.body = "Sorry we do not have this resource."; } function *printHelloMessage(){ this.status = 200; this.body = "Hey there!"; } function *handle404Errors(next){ if (404 != this.status) return; this.redirect('/not_found'); } app.listen(3000);When we run this code and navigate to any route other than /hello, we'll be redirected to /not_found. We have placed the middleware at the end(app.use function call to this middleware). This ensures we reach the middleware at last and send the corresponding response. Following are the results we see when we run the above code:
When you navigate to https://localhost:3000/hello, you get:
If you navigate to any other route, you'll get:
No comments:
Post a Comment