微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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);

原文地址:https://www.jb51.cc/nodejs/241169.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐