2016-10-21 2 views
0

Plattform Knoten: v-4.4.5 koa: v-2.0.0 koa-Router: v-7.0.0koa-Router 404 auf node.js

hier ist mein Code

///<reference path="../typings/tsd.d.ts" /> 
 
//导入koa,和koa 1.x不同,在koa2中,我们导入的是一个class,因此用大写的Koa表示: 
 
var Koa = require('koa'); 
 

 
var router=require("koa-router")(); 
 

 

 
// 创建一个Koa对象表示web app本身: 
 
var app = new Koa(); 
 

 
// parse request body: 
 

 

 
//add url-route: 
 
router.get('/hello/:name', (ctx, next) => { 
 
    var name = ctx.params.name; 
 
    ctx.response.body =`<h1>Hello, ${name}!</h1>`; 
 
}); 
 

 
router.get('/', function *(ctx, next) { 
 
    ctx.response.body = '<h1>Index</h1>'; 
 
}); 
 

 
router.all('/login', function *() { 
 
    this.redirect('/'); 
 
    this.status = 301; 
 
}); 
 

 
app.use(function (ctx,next){ 
 
    this.body = `Invalid URL!!!${ctx.request.method} ${ctx.request.url}`; 
 
    ctx.response.type = 'text/html'; 
 
    ctx.response.body = this.body; 
 
}); 
 

 
app.use(router.routes()) 
 
.use(router.allowedMethods()); 
 
// 在端口3000监听: 
 
app.listen(3000); 
 
console.log('app started at port 3000...');

, wenn ich 'Ungültige URL !!!' Brower http://localhost:3000/,output. Sag mir, warum kann '/' Router nicht übereinstimmen? Danke!

Antwort

0

aktualisieren Sie Ihre Knotenversion auf 7.6.0. koa2 Arbeit an> = 7.6.0 und Code wie

Koa=require('koa') 
    var app = new Koa(); 
    router = require('koa-router')() 
    // parse request body: 


    //add url-route: 
    router.get('/hello/:name', (ctx, next) => { 
     var name = ctx.params.name; 
     ctx.response.body =`<h1>Hello, ${name}!</h1>`; 
    }); 

    router.get('/', function (ctx, next) { 
     console.log(ctx.request); 
     ctx.body = '<h1>Index</h1>'; 
    }); 

    router.all('/login', function (ctx) { 
     ctx.redirect('/'); 
     ctx.status = 301; 
    }); 

    app.use(function (ctx,next){ 
     this.body = `Invalid URL!!!${ctx.request.method} ${ctx.request.url}`; 
     ctx.response.type = 'text/html'; 
     ctx.response.body = this.body; 
     next() 
    }); 

    app.use(router.routes()) 
    .use(router.allowedMethods()); 
    // 在端口3000监听: 
    app.listen(3000); 
    console.log('app started at port 3000...'); 
1

können Sie '*' Urls wie 404 oder ungültige Links entsprechen:

router.all('*', function(ctx, next) { 
    // 
});