search

Home  >  Q&A  >  body text

node.js - koa-router的路由独立出来不好使

koa-generator生成的koa框架

localhost:3000/可以访问
localhost:3000/hi 不可以访问
localhost:3000/users 可以访问
localhost:3000//users/hi 可以访问

以前学过express,同样的结构没有问题

以下是代码
app.js

const Koa = require('koa');
const app = new Koa();
const router = require('koa-router')();
const views = require('koa-views');
const co = require('co');
const convert = require('koa-convert');
const json = require('koa-json');
const onerror = require('koa-onerror');
const bodyparser = require('koa-bodyparser')();
const logger = require('koa-logger');

const index = require('./routes/index');
const users = require('./routes/users');

// middlewares
app.use(convert(bodyparser));
app.use(convert(json()));
app.use(convert(logger()));
app.use(require('koa-static')(__dirname + '/public'));

app.use(views(__dirname + '/views', {
  extension: 'jade'
}));


// logger
app.use(async (ctx, next) => {
  const start = new Date();
  await next();
  const ms = new Date() - start;
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});

router.use('/', index.routes(), index.allowedMethods());
router.use('/users', users.routes(), users.allowedMethods());

app.use(router.routes(), router.allowedMethods());
// response





app.on('error', function(err, ctx){
  console.log(err)
  logger.error('server error', err, ctx);
});


module.exports = app;

routes里两个文件,index.js

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

router.get('/', function (ctx) {
  ctx.body = 'this a index response!';
});


router.get('/hi', function (ctx) {
  ctx.body = 'this a index/hi response!';
});


module.exports = router;

users.js

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

router.get('/', function (ctx, next) {
  ctx.body = 'this a users response!';
});


router.get('/ok', function (ctx, next) {
  ctx.body = 'this a users/ok response!';
});

module.exports = router;
迷茫迷茫2785 days ago487

reply all(1)I'll reply

  • PHPz

    PHPz2017-04-17 15:39:16

    The principle of

    koa-router is to merge the two paths together, so according to your code path it should be: nested routers

    localhost:3000/
    # 下面这个路径有问题
    localhost:3000//hi
    localhost:3000/users/
    localhost:3000/users/ok

    So

    cannot be matchedlocalhost:3000/hi

    There are two ways to modify it:

    1. Change

      to router.use('/', index.routes(), index.allowedMethods());router.use('', index.routes(), index.allowedMethods());

    2. Change

      to router.get('/hi', function (ctx){})router.get('hi', function (ctx){})

    If the subject accesses

    , it is also inaccessible. It is not that there is no match, but that koa thinks that the path is localhost:3000//hi and throws 400 directly. The Malicious Path link is not reached at all. See the code: https://github.com/pillarjs/r...koa-router

    prefix reference source code: https://github.com/alexmingoi...

    reply
    0
  • Cancelreply