Node.js Koa路由器路由不使用';不存在

Node.js Koa路由器路由不使用';不存在,node.js,koa,Node.js,Koa,我不敢相信没有简单的答案可以做到这一点。 我想重新定向,比如说 www.example.com/this-url-does-not-exist 到 一定有办法,所有有koajs的nodejs网站都不会崩溃?我的路由器膝关节炎(我使用膝关节炎与KOA路由器):< /P> 路由器 .get(“/”,函数*(下一步){ this.body=“public:/”; }) .get('/about',函数*(下一步){ this.body=“public:/about”; }) .get('*',fun

我不敢相信没有简单的答案可以做到这一点。 我想重新定向,比如说

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

一定有办法,所有有koajs的nodejs网站都不会崩溃?我的路由器膝关节炎(我使用膝关节炎与KOA路由器):< /P>
路由器
.get(“/”,函数*(下一步){
this.body=“public:/”;
})
.get('/about',函数*(下一步){
this.body=“public:/about”;
})

.get('*',function*(next){/JAMES MOORES的答案是正确的;不要听我说

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: /(|^$)/';
    });
公共路由器 .get(“/”,函数*(下一步){ console.log('public:/'); this.body='public:/'; }) .get('/about',函数*(下一步){ log('public:/about'); this.body='public:/about'; })
.get(/(|^$)/,function*(next){/如果您不喜欢正则表达式,请执行以下操作:

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

我只想说我喜欢你的标记。匹配“*”或router.DEFAULT_ROUTE等会很有意义,可能应该添加。事实上,我正在考虑为此编写一个完整的请求。我只想指出,这非常有效。如果你有一个前端SPA,它使用或不使用哈希标记,它将继续工作使用您将服务器前端的url仍按要求设置。
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: /(|^$)/';
    });
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);