获取Koa的实际路线

时间:2018-10-15 12:05:12

标签: node.js koa koa-router

我是koa的新手。我需要在koa请求中获得一条实际路线。

示例1:如果我打了一条路线/user,并且得到了ctx原始网址/user/

示例2:如果我打了一条路线user/:id,并且得到了ctx原始网址/user/1

我尝试获取

之类的路径
exports.checkAuth = async ctx => {
   console.log(ctx.originalUrl); // return -> /user/1
   console.log(ctx.path); // return -> /user/1
 };

我想在每个请求中获取诸如user/:id之类的实际路径。

在快速路线中,获得这样的实际路径

 app.get('/user/:id', function userIdHandler(req, res) {
     console.log(req.route);
 });

输出:

{ path: '/user/:id',
stack:
   [ { handle: [Function: userIdHandler],
   name: 'userIdHandler',
   params: undefined,
   path: undefined,
   keys: [],
   regexp: /^\/?$/i,
   method: 'get' } ],
methods: { get: true } }

1 个答案:

答案 0 :(得分:0)

在koa.js中,当路由匹配时,其路径可在core.js:1673 ERROR TypeError: Observable_1.Observable.of is not a function at Droppable.push../node_modules/ng-drag-drop/src/directives/droppable.directive.js.Droppable.allowDrop (droppable.directive.js:151) at SafeSubscriber._next (droppable.directive.js:161) at SafeSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub (Subscriber.js:195) at SafeSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next (Subscriber.js:133) at Subscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._next (Subscriber.js:77) at Subscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:54) at Subject.push../node_modules/rxjs/_esm5/internal/Subject.js.Subject.next (Subject.js:47) at Draggable.push../node_modules/ng-drag-drop/src/directives/draggable.directive.js.Draggable.dragStart (draggable.directive.js:112) at Object.eval [as handleEvent] (CustodianCardComponent.html:1) at handleEvent (core.js:10251) 处使用,如果已命名,则其名称可在ctx._matchedRoute处使用

ctx._matchedRouteName->您的情况下将返回ctx._matchedRoute

请记住,ctx._matchedRoute是user/:id的一部分。