Koa-router route URLs that do not exist

I can not believe that there is no simple answer. I want to redirect, say:

www.example.com/this-url-does-not-exist 

to

 www.example.com/ 

There has to be a way, all the hub sites with koajs just can't crash? Heres my router (I use koa with koa-router):

 router .get('/', function* (next) { this.body = "public: /"; }) .get('/about', function* (next) { this.body = "public: /about"; }) .get('*', function* (next) { // <--- wildcard * doesn't work this.body = "public: *"; }); 

And don’t tell me to use regular expressions, I tried with them too, and this means that you manually update the expression when adding URLs, etc., which is not what I am looking for, plus it does not work since javascript does not support negative images.

+5
source share
2 answers

If you do not want the regex to not do something like this:

 var koa = require('koa'), router = require('koa-router')(), app = koa(); router.get('/path1', function *(){ this.body = 'Path1 response'; }); router.get('/path2', function *(){ this.body = 'Path2 response'; }); app.use(router.routes()) app.use(router.allowedMethods()); // catch all middleware, only land here // if no other routing rules match // make sure it is added after everything else app.use(function *(){ this.body = 'Invalid URL!!!'; // or redirect etc // this.redirect('/someotherspot'); }); app.listen(3000); 
+9
source

JAMES MORES ANSWER CORRECTLY; DO NOT LISTEN TO ME!

 publicRouter .get('/', function* (next) { console.log('public: /'); this.body = 'public: /'; }) .get('/about', function* (next) { console.log('public: /about'); this.body = 'public: /about'; }) .get(/(|^$)/, function* (next) { // <--- important that it is last console.log('public: /(|^$)/'); this.body = 'public: /(|^$)/'; }); 

The .get router does not report that .get depends on what order it adds to the code. Therefore, putting it at the end with the regular expression /(|^$)/ , works.

However, this interferes with using koa-mount to mount other routers.

0
source

Source: https://habr.com/ru/post/1216024/


All Articles