node.js – 不存在的Koa-router路由URL

我无法相信这样做没有简单的答案.
我想重定向让我们说;
www.example.com/this-url-does-not-exist

www.example.com/

必须有一种方法,所有与koajs的nodejs网站都无法崩溃?继承人我的路由器(我使用koa与koa路由器):

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: *";
    });

并且不要告诉我使用正则表达式,我一直在尝试并使用它们,这意味着在添加URL时手动更新表达式等等,这不是我想要的,而且它不能用于javascript不支持消极的外观.

解决方法

如果您不喜欢正则表达式,请执行以下操作:
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);

相关文章

这篇文章主要介绍“基于nodejs的ssh2怎么实现自动化部署”的...
本文小编为大家详细介绍“nodejs怎么实现目录不存在自动创建...
这篇“如何把nodejs数据传到前端”文章的知识点大部分人都不...
本文小编为大家详细介绍“nodejs如何实现定时删除文件”,内...
这篇文章主要讲解了“nodejs安装模块卡住不动怎么解决”,文...
今天小编给大家分享一下如何检测nodejs有没有安装成功的相关...