简体   繁体   中英

koa-router 404 on node.js

platform node: v-4.4.5 koa: v-2.0.0 koa-router: v-7.0.0

here is my 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...'); 

when I Brower http://localhost:3000/,output 'Invalid URL!!!'. tell me why can't match '/' router ? thank you!

you can use '*' to match urls like 404 or invalid links:

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

upgrade your node version to 7.6.0. koa2 work on >=7.6.0 and code like

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM