Redirection is very important when creating websites. If a malformed URL is requested or there are some errors on your server, you should redirect them to the respective error pages. Redirects can also be used to keep people out of restricted areas of your website.
Let us create an error page and redirect to that page whenever someone requests a malformed URL.
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 we navigate to https://localhost:3000/hello, we get −
If we navigate to any other route, we get −