Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Koa-router route urls that don't exist

Tags:

node.js

koa

I can't believe there is no easy answer to do this. I wish to redirect let's say;

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

to

www.example.com/

There has to be a way, all the nodejs websites with koajs just can't crash? Heres my router (I'm using 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've been trying and with them and it means manually updating the expression when adding urls etc. which is not what I've looking for, plus it doesn't work as javascript does not support negative lookbehinds.

like image 414
basickarl Avatar asked Mar 24 '15 21:03

basickarl


1 Answers

If you prefer no regex 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);
like image 86
James Moore Avatar answered Nov 24 '22 10:11

James Moore