繁体   English   中英

node.js上的koa-router 404

[英]koa-router 404 on node.js

平台节点:v-4.4.5 koa:v-2.0.0 koa-router:v-7.0.0

这是我的代码

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

当我浏览http:// localhost:3000 /时,输出 “无效的URL !!!”。 告诉我为什么不能匹配“ /”路由器? 谢谢!

您可以使用“ *”来匹配404之类的网址或无效链接:

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

将您的节点版本升级到7.6.0。 koa2在> = 7.6.0上工作并且代码像

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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